angular面試題及答案_關于最流行的Angular問題的StackOverflow上的48個答案

angular面試題及答案

by Shlomi Levi

通過Shlomi Levi

關于最流行的Angular問題的StackOverflow上的48個答案 (48 answers on StackOverflow to the most popular Angular questions)

I gathered the most common questions and answers from Stackoverflow. These questions were chosen by the highest score received. Whether you are an expert or a beginner, you can learn from others’ experiences.

我從Stackoverflow收集了最常見的問題和解答。 這些問題是根據獲得的最高分數來選擇的。 無論您是專家還是初學者,都可以從他人的經驗中學到東西。

目錄 (Table of Contents)

  • Angular — Promise vs Observable

    角度—承諾與可觀察

  • Difference between Constructor and ngOnInit

    構造函數和ngOnInit之間的區別

  • Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’

    無法綁定到“ ngModel”,因為它不是“ input”的已知屬性

  • Angular HTML binding

    角度HTML綁定

  • Angular/RxJs When should I unsubscribe from `Subscription`

    Angular / RxJs我應該何時退訂`Subscription`

  • How can I select an element in a component template?

    如何在組件模板中選擇元素?

  • What is the equivalent of ngShow and ngHide in Angular?

    Angular中的ngShow和ngHide等效于什么?

  • How to bundle an Angular app for production

    如何捆綁Angular應用進行生產

  • BehaviorSubject vs Observable?

    BehaviorSubject與Observable?

  • @Directive v/s @Component in Angular

    @Directive v / s @Component在Angular中

  • Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]

    帶有TypeScript錯誤http.get(…).map的角度HTTP GET不是[null]中的函數

  • How to use jQuery with Angular?

    如何在Angular中使用jQuery?

  • Angular EXCEPTION: No provider for Http

    Angular EXCEPTION:沒有Http的提供程序

  • Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’

    無法綁定到“ formGroup”,因為它不是“ form”的已知屬性

  • Angular DI Error — EXCEPTION: Can’t resolve all parameters

    角度DI錯誤—例外:無法解析所有參數

  • Angular — Set headers for every request

    Angular —為每個請求設置標題

  • How to use *ngIf else in Angular?

    如何在Angular中使用* ngIf else?

  • Angular no provider for NameService

    Angular沒有NameService提供程序

  • Binding select element to object in Angular

    將選擇元素綁定到Angular中的對象

  • What is difference between declarations, providers and import in NgModule

    NgModule中的聲明,提供程序和導入之間有什么區別

  • In Angular, how do you determine the active route?

    在Angular中,如何確定活動路線?

  • Angular CLI SASS options

    Angular CLI SASS選項

  • Triggering change detection manually in Angular

    在Angular中手動觸發變化檢測

  • Angular and Typescript: Can’t find names

    Angular和Typescript:找不到名稱

  • Angular — What is the meanings of module.id in component?

    角度—組件中module.id的含義是什么?

  • How can I get new selection in “select” in Angular 2?

    如何在Angular 2的“選擇”中獲得新選擇?

  • Angular exception: Can’t bind to ‘ngForIn’ since it isn’t a known native property

    角度異常:無法綁定到“ ngForIn”,因為它不是已知的本機屬性

  • *ngIf and *ngFor on same element causing error

    * ngIf和* ngFor在同一元素上導致錯誤

  • What is the Angular equivalent to an AngularJS $watch?

    Angular等效于AngularJS $ watch?

  • Importing lodash into angular2 + typescript application

    將lodash導入angular2 +打字稿應用程序

  • How to detect a route change in Angular?

    如何在Angular中檢測路線變化?

  • Global Events in Angular

    Angular中的全球事件

  • What are differences between SystemJS and Webpack?

    SystemJS和Webpack有什么區別?

  • Angular: Can’t find Promise, Map, Set and Iterator

    角度:找不到Promise,Map,Set和Iterator

  • Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0

    Angular RC4 —帶有打字稿2.0.0的Angular ^ 2.0.0

  • How to detect when an @Input() value changes in Angular?

    如何檢測Angular中@Input()值何時更改?

  • How to pass url arguments (query string) to a HTTP request on Angular

    如何將url參數(查詢字符串)傳遞給Angular上的HTTP請求

  • How do you deploy Angular apps?

    您如何部署Angular應用程序?

  • ngFor with index as value in attribute

    ngFor,其中索引作為屬性中的值

  • Define global constants in Angular 2

    在Angular 2中定義全局常量

  • Angular — Use pipes in services and components

    角度—在服務和組件中使用管道

  • Angular2 Exception: Can’t bind to ‘routerLink’ since it isn’t a known native property

    Angular2異常:由于它不是已知的本機屬性,因此無法綁定到“ routerLink”

  • Angular 2 dynamic tabs with user-click chosen components

    帶有用戶單擊所選組件的Angular 2動態選項卡

  • Delegation: EventEmitter or Observable in Angular

    委托:EventEmitter或可觀察到的Angular

  • How to add bootstrap to an angular-cli project

    如何將引導程序添加到angular-cli項目

  • access key and value of object using *ngFor

    使用* ngFor訪問對象的鍵和值

  • Angular exception: Can’t bind to ‘ngFor’ since it isn’t a known native property

    角度異常:無法綁定到“ ngFor”,因為它不是已知的本機屬性

  • How to add font-awesome to Angular 2 + CLI project

    如何將真棒字體添加到Angular 2 + CLI項目

  • Difference between HTTP and HTTPClient in angular 4?

    HTTP和HTTPClient在角度4中的區別?

Enjoy!

請享用!

角度—承諾與可觀察 (Angular — Promise vs Observable)

551+ points ? 150,497+ viewed

551+分 已查看1 50,497+

551+ points ? 150,497+ viewed Rohit asked,

551+分 羅希特(Rohit)問過 1 50,497+次觀看

Can someone please explain the difference between Promise and Observable in Angular?

有人可以解釋Angular中PromiseObservable之間的區別嗎?

An example on each would be helpful in understanding both the cases. In what scenario can we use each case?

每個示例均有助于理解這兩種情況。 在什么情況下我們可以使用每種情況?

Günter Z?chbauer answered, (686+ points)

GünterZ?chbauer 回答了,(686分以上)

Promise

諾言

A Promise handles a single event when an async operation completes or fails.

當異步操作完成或失敗時, Promise處理單個事件

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

注意:那里有Promise庫支持取消,但是ES6 Promise到目前為止還不支持。

Observable

可觀察的

An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.

一個Observable就像一個Stream (在許多語言中),并且允許傳遞零個或多個事件,其中每個事件都被調用回調。

Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.

通常, ObservablePromise更為可取,因為它提供了Promise等功能。 使用Observable ,您要處理0、1或多個事件都沒有關系。 在每種情況下,您都可以使用相同的API。

Observable also has the advantage over Promise to be cancelable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.

Promise相比, Observable也具有可取消的優勢。 如果不再需要對服務器的HTTP請求或其他昂貴的異步操作的結果,則ObservableSubscription可以取消該預訂,而Promise最終將調用成功或失敗的回調,即使您不需要需要通知或它提供的結果了。

Observable provides operators like map, forEach, reduce, ... similar to an array

Observable提供類似于mapforEachreduce ,...的運算符 ,類似于數組

There are also powerful operators like retry(), or replay(), ... that are often quite handy.

還有一些功能強大的運算符,例如retry()replay() ……通常非常方便。

SourceTop

來源 頂部

構造函數和ngOnInit之間的區別 (Difference between Constructor and ngOnInit)

444+ points ? 190,166+ viewed

444+分 已查看1 90,166+

444+ points ? 190,166+ viewed Haseena P A asked,

444+分 已查看1 90166則以上Haseena PA的問題,

Angular provides lifecycle hook ngOnInit by default.

Angular默認提供生命周期掛鉤ngOnInit

Why should ngOnInit be used, if we already have a constructor?

如果我們已經有了constructor ,為什么還要使用ngOnInit呢?

Pardeep Jain answered, (512+ points)

Pardeep Jain 回答了,(512分以上)

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like

Constructor是該類的默認方法,該方法在實例化該類時執行,并確保該類及其子類中字段的正確初始化。 有角或更好的依賴注入器(DI)分析構造函數參數,并在通過調用new MyClass()創建新實例時嘗試尋找與構造函數參數類型匹配的提供程序,將其解析并將其傳遞給構造函數,例如

new MyClass(someArg);

ngOnInit is a lifecycle hook called by Angular2 to indicate that Angular is done creating the component.

ngOnInitngOnInit調用的生命周期掛鉤,以指示Angular已完成創建組件。

We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice):

我們必須導入OnInit才能這樣使用(實際上,強制實施OnInit不是強制性的,但被認為是好的做法):

import {Component, OnInit} from '@angular/core';

then to use the method of OnInit we have to implement in the class like this.

然后要使用OnInit的方法,我們必須在此類中實現。

export class App implements OnInit{constructor(){//called first time before the ngOnInit()}ngOnInit(){//called after the constructor and called  after the first ngOnChanges() }
}

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

通常,我們將ngOnInit用于所有的初始化/聲明,并避免在構造函數中起作用。 構造函數應僅用于初始化類成員,而不應執行實際的“工作”。

So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

因此,您應該使用constructor()來設置依賴注入,而無需過多設置。 ngOnInit()是“開始”的更好位置-解析組件綁定的位置/位置。

For more information refer here:

有關更多信息,請參見此處:

  • https://angular.io/api/core/OnInit

    https://angular.io/api/core/OnInit

  • Angular 2 Component Constructor Vs OnInit

    Angular 2組件構造函數與OnInit

SourceTop

來源 頂部

無法綁定到“ ngModel”,因為它不是“ input”的已知屬性 (Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’)

442+ points ? 246,901+ viewed

442+點 已查看2 46,901+

442+ points ? 246,901+ viewed abreneliere asked,

442+點 2 46,901+瀏覽過abreneliere詢問,

I’ve got the following error when launching my Angular app, even if the component is not displayed.

即使未顯示組件,啟動我的Angular應用程序時也會出現以下錯誤。

I have to comment out the so that my app works.

我必須注釋掉,這樣我的應用才能正常工作。

zone.js:461 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("<div><label>Created:</label><input  type="text" [ERROR ->][(ngModel)]="test" placeholder="foo" /></div>
</div>"): InterventionDetails@4:28 ; Zone: <root> ; Task: Promise.then ; Value:

I’m looking at the Hero plucker but I don’t see any difference.

我在看英雄拔毛器,但沒什么區別。

Here is the component file:

這是組件文件:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Intervention } from '../../model/intervention';@Component({selector: 'intervention-details',templateUrl: 'app/intervention/details/intervention.details.html',styleUrls: ['app/intervention/details/intervention.details.css']
})export class InterventionDetails
{@Input() intervention: Intervention;public test : string = "toto";
}

abreneliere answered, (674+ points)

abreneliere 回答了,(674+分)

Yes that’s it, in the app.module.ts, I just added :

是的就是這樣,在app.module.ts中,我剛剛添加了:

import { FormsModule } from '@angular/forms';[...]@NgModule({imports: [[...]FormsModule],[...]
})

SourceTop

來源 頂部

角度HTML綁定 (Angular HTML binding)

385+ points ? 227,115+ viewed

385+分 已查看2 27,115+

385+ points ? 227,115+ viewed Aviad P. asked,

385+分 2 27,115+查看過Aviad P.問,

I am writing an Angular application, and I have an HTML response I want to display. How do I do that? If I simply use the binding syntax {{myVal}} it encodes all HTML characters (of course).

我正在編寫Angular應用程序,并且要顯示HTML響應。 我怎么做? 如果我僅使用綁定語法{{myVal}}它將對所有HTML字符進行編碼(當然)。

I need somehow to bind the inner html of a div to the variable value.

我需要以某種方式將div的內部html綁定到變量值。

prolink007 answered, (691+ points)

prolink007 回答,(超過691分)

The correct syntax is now the following:

現在,正確的語法如下:

<div [innerHTML]="theHtmlString"></div>

Working in 5.2.6

5.2.6工作

Documentation Reference

文檔參考

SourceTop

來源 頂部

Angular / RxJs我應該何時退訂`Subscription` (Angular/RxJs When should I unsubscribe from `Subscription`)

320+ points ? 69,606+ viewed

320+分 已查看6 9,606+

320+ points ? 69,606+ viewed Sergey Tihon asked,

320+分 6 9,606+瀏覽過Sergey Tihon 問,

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy lifecycle and when can I simply ignore them?

我應該何時在NgOnDestroy生命周期中存儲Subscription實例并調用unsubscribe() ,何時可以忽略它們?

Saving all subscriptions introduces a lot of mess into component code.

保存所有訂閱會在組件代碼中帶來很多麻煩。

HTTP Client Guide ignore subscriptions like this:

HTTP客戶端指南會忽略這樣的訂閱:

getHeroes() {this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes,error =>  this.errorMessage = <any>error);
}

In the same time Route & Navigation Guide says that:

同時,《 路線與導航指南 》指出:

Eventually, we'll navigate somewhere else. The router will remove this component from the DOM and destroy it. We need to clean up after ourselves before that happens. Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.

Eventually, we'll navigate somewhere else. The router will remove this component from the DOM and destroy it. We need to clean up after ourselves before that happens. Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.

We unsubscribe from our Observable in the ngOnDestroy method.

We unsubscribe from our Observable in the ngOnDestroy method.

private sub: any;ngOnInit() {this.sub = this.route.params.subscribe(params => {let id = +params['id']; // (+) converts string 'id' to a numberthis.service.getHero(id).then(hero => this.hero = hero);});
}ngOnDestroy() {this.sub.unsubscribe();
}

seangwright answered, (508+ points)

seangwright 回答,(超過508分)

— —編輯3 —“官方”解決方案(2017/04/09) (— — Edit 3 — The ‘Official’ Solution (2017/04/09))

I spoke with Ward Bell about this question at NGConf (I even showed him this answer which he said was correct) but he told me the docs team for Angular had a solution to this question that is unpublished (though they are working on getting it approved). He also told me I could update my SO answer with the forthcoming official recommendation.

我在NGConf上與Ward Bell談到了這個問題(我什至向他展示了這個答案,他說的是正確的),但是他告訴我Angular的文檔小組對這個問題的解決方案尚未發布(盡管他們正在努力使其獲得批準) )。 他還告訴我,我可以通過即將提出的官方建議來更新我的SO答案。

The solution we should all use going forward is to add a private ngUnsubscribe: Subject = new Subject(); field to all components that have .subscribe() calls to Observables within their class code.

今后我們應該使用的解決方案是添加一個private ngUnsubscribe: Subject = new Subject(); 所有在其類代碼中具有.subscribe()調用Observable的組件的字段。

We then call this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); in our ngOnDestroy() methods.

然后,我們將其稱為this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); 在我們的ngOnDestroy()方法中。

The secret sauce (as noted already by @metamaker) is to call .takeUntil(this.ngUnsubscribe) before each of our .subscribe() calls which will guarantee all subscriptions will be cleaned up when the component is destroyed.

秘訣(如@metamaker所述 )是在我們的每個.subscribe()調用之前調用.takeUntil(this.ngUnsubscribe) ,這將確保在銷毀組件時清除所有訂閱。

Example:

例:

import { Component, OnDestroy, OnInit } from '@angular/core';
import 'rxjs/add/operator/takeUntil';
// import { takeUntil } from 'rxjs/operators'; // for rxjs ^5.5.0 lettable operators
import { Subject } from 'rxjs/Subject';import { MyThingService } from '../my-thing.service';@Component({selector: 'my-thing',templateUrl: './my-thing.component.html'
})
export class MyThingComponent implements OnDestroy, OnInit {private ngUnsubscribe: Subject = new Subject();constructor(private myThingService: MyThingService,) { }ngOnInit() {this.myThingService.getThings().takeUntil(this.ngUnsubscribe).subscribe(things => console.log(things));/* if using lettable operators in rxjs ^5.5.0this.myThingService.getThings().pipe(takeUntil(this.ngUnsubscribe)).subscribe(things => console.log(things));*/this.myThingService.getOtherThings().takeUntil(this.ngUnsubscribe).subscribe(things => console.log(things));}ngOnDestroy() {this.ngUnsubscribe.next();this.ngUnsubscribe.complete();}
}

-編輯2(2016/12/28) (— — Edit 2 (2016/12/28))

Source 5

來源5

The Angular tutorial, the Routing chapter now states the following: “The Router manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don’t need to unsubscribe from the route params Observable.” — Mark Rajcok

Angular教程的“路由”一章現在指出以下內容:“路由器管理它提供的可觀察對象并本地化訂閱。 當組件被銷毀時,訂閱將被清除,以防止內存泄漏,因此我們無需取消訂閱可觀察到的路由參數。” — 馬克·拉杰克 ( Mark Rajcok)

Here’s a discussion on the Github issues for the Angular docs regarding Router Observables where Ward Bell mentions that clarification for all of this is in the works.

這是針對有關Router Observables的Angular文檔的Github問題的討論 ,Ward Bell提到正在為所有這些澄清。

— —編輯1 (— — Edit 1)

Source 4

來源4

In this video from NgEurope Rob Wormald also says you do not need to unsubscribe from Router Observables. He also mentions the http service and ActivatedRoute.params in this video from November 2016.

在NgEurope的這段視頻中, Rob Wormald還說您不需要取消訂閱Router Observables。 他還在2016年11月的視頻中提到了http服務和ActivatedRoute.params

— —原始答案 (— — Original Answer)

TLDR:

TLDR:

For this question there are (2) kinds of Observables - finite value and infinite value.

對于此問題,有(2)種Observables值- 有限值和無限值。

http Observables produce finite (1) values and something like a DOM event listener Observables produce infinite values.

http Observables產生有限 (1)值,類似DOM event listener東西Observables產生無限值。

If you manually call subscribe (not using async pipe), then unsubscribe from infinite Observables.

如果您手動調用subscribe (不使用異步管道),則unsubscribe 無限的 Observables

Don’t worry about finite ones, RxJs will take care of them.

不必擔心有限RxJs會照顧他們。

Source 1

來源1

I tracked down an answer from Rob Wormald in Angular’s Gitter here.

我在這里從Angular的Gitter中找到了 Rob Wormald的答案。

He states (i reorganized for clarity and emphasis is mine)

他指出(為清晰起見,我進行了重組,重點是我的)

if it's a single-value-sequence (like an http request) the manual cleanup is unnecessary (assuming you subscribe in the controller manually)

if it's a single-value-sequence (like an http request) the manual cleanup is unnecessary (assuming you subscribe in the controller manually)

i should say "if it's a sequence that completes" (of which single value sequences, a la http, are one)

i should say "if it's a sequence that completes " (of which single value sequences, a la http, are one)

if it's an infinite sequence, you should unsubscribe which the async pipe does for you

if it's an infinite sequence , you should unsubscribe which the async pipe does for you

Also he mentions in this youtube video on Observables that they clean up after themselves... in the context of Observables that complete (like Promises, which always complete because they are always producing 1 value and ending - we never worried about unsubscribing from Promises to make sure they clean up xhr event listeners, right?).

他還在YouTube上有關Observables的視頻中提到, they clean up after themselves ……在complete的Observables的背景下(例如Promises,由于它們總是產生1值并結束,所以它們總是完成的-我們從不擔心從Promises退訂到確保他們清理了xhr事件監聽器,對吧?)。

Source 2

來源2

Also in the Rangle guide to Angular 2 it reads

同樣在Angular 2的Rangle指南中

In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time.

In most cases we will not need to explicitly call the unsubscribe method unless we want to cancel early or our Observable has a longer lifespan than our subscription. The default behavior of Observable operators is to dispose of the subscription as soon as .complete() or .error() messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time.

When does the phrase our Observable has a longer lifespan than our subscription apply?

什么時候our Observable has a longer lifespan than our subscription短語our Observable has a longer lifespan than our subscription

It applies when a subscription is created inside a component which is destroyed before (or not ‘long’ before) the Observable completes.

它適用于在組件內部創建預訂,而該組件在Observable完成之前被銷毀(或未“長久”)的情況。

I read this as meaning if we subscribe to an http request or an observable that emits 10 values and our component is destroyed before that http request returns or the 10 values have been emitted, we are still ok!

我的意思是,如果我們訂閱一個http請求或一個發出10個值的Observable,并且在該http請求返回或發出10個值之前銷毀了我們的組件,我們還是可以的!

When the request does return or the 10th value is finally emitted the Observable will complete and all resources will be cleaned up.

當請求確實返回或最終發出第十個值時, Observable將完成,所有資源將被清理。

Source 3

來源3

If we look at this example from the same Rangle guide we can see that the Subscription to route.params does require an unsubscribe() because we don't know when those params will stop changing (emitting new values).

如果我們從相同的Rangle指南中查看此示例 ,則可以看到對route.paramsSubscription確實需要unsubscribe()因為我們不知道這些params何時會停止更改(發出新值)。

The component could be destroyed by navigating away in which case the route params will likely still be changing (they could technically change until the app ends) and the resources allocated in subscription would still be allocated because there hasn’t been a completion.

通過導航可以破壞該組件,在這種情況下,路由參數可能仍會更改(它們可能會在技術上更改,直到應用程序結束),并且由于尚未completion因此仍將分配訂閱中分配的資源。

SourceTop

來源 頂部

如何在組件模板中選擇元素? (How can I select an element in a component template?)

263+ points ? 265,966+ viewed

263+分 已查看2 65,966+

263+ points ? 265,966+ viewed Aman Gupta asked,

263+分 2 65,966+瀏覽過Aman Gupta問,

Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$.

有人知道如何掌握組件模板中定義的元素嗎? 使用$$$可以使Polymer變得非常容易。

I was just wondering how to go about it in Angular.

我只是想知道如何在Angular中進行操作。

Take the example from the tutorial:

從教程中獲取示例:

import {Component} from '@angular/core'@Component({selector:'display'template:`<input #myname(input)="updateName(myname.value)"/><p>My name : {{myName}}</p>`})
export class DisplayComponent {myName: string = "Aman";updateName(input: String) {this.myName = input;}
}

How do I catch hold of a reference of the p or input element from within the class definition?

如何從類定義中抓住對pinput元素的引用?

Brocco answered, (149+ points)

布羅科 (149)

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor:

您可以通過將ElementRef注入到組件的構造函數中來通過ElementRef獲取DOM元素的句柄:

constructor(myElement: ElementRef) { ... }

Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

文件: https : //angular.io/docs/ts/latest/api/core/index/ElementRef-class.html

SourceTop

來源 頂部

Angular中的ngShow和ngHide等效于什么? (What is the equivalent of ngShow and ngHide in Angular?)

261+ points ? 206,651+ viewed

261+分 已查看2 06,651+

261+ points ? 206,651+ viewed Mihai R?ducanu asked,

261+分 2 06,651+瀏覽了MihaiR?ducanu 問,

I have a number of elements that I want to be visible under certain conditions.

在某些條件下,我希望看到一些元素。

In AngularJS I would write

在AngularJS中,我會寫

<div ng-show="myVar">stuff</div>

How can I do this in Angular?

如何在Angular中做到這一點?

Günter Z?chbauer answered, (445+ points)

GünterZ?chbauer 回答了,(445分以上)

Just bind to the hidden property

只需綁定到hidden屬性

[hidden]="!myVar"

See also

也可以看看

  • https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden

    https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes/hidden

issues

問題

hidden has some issues though because it can conflict with CSS for the display property.

hidden有一些問題,因為它可能與display屬性CSS沖突。

See how some in Plunker example doesn't get hidden because it has a style

看看在Plunker示例中如何隱藏some樣式,因為它具有樣式

:host {display: block;}

set. (This might behave differently in other browsers — I tested with Chrome 50)

組。 (這在其他瀏覽器中可能會有所不同-我在Chrome 50上進行了測試)

workaround

解決方法

You can fix it by adding

您可以通過添加來修復它

[hidden] { display: none !important;}

To a global style in index.html.

index.html的全局樣式。

another pitfall

另一個陷阱

hidden="false"
hidden="{{false}}"
hidden="{{isHidden}}" // isHidden = false;

are the same as

與...相同

hidden="true"

and will not show the element.

并且不會顯示該元素。

hidden="false" will assign the string "false" which is considered truthy.Only the value false or removing the attribute will actually make the element visible.

hidden="false"將分配被認為是真實的字符串"false"只有值false或刪除屬性才能使該元素可見。

Using {{}} also converts the expression to a string and won't work as expected.

使用{{}}還會將表達式轉換為字符串,將無法正常工作。

Only binding with [] will work as expected because this false is assigned as false instead of "false".

只有與[]綁定才能按預期工作,因為此false被分配為false而不是"false"

*ngIf vs [hidden]

*ngIf [hidden]

*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

*ngIf有效地從DOM中刪除了它的內容,而[hidden]修改了display屬性,僅指示瀏覽器不顯示內容,但DOM仍然包含它。

SourceTop

來源 頂部

如何捆綁Angular應用進行生產 (How to bundle an Angular app for production)

258+ points ? 111,603+ viewed

258+分 已查看1 11,603+

258+ points ? 111,603+ viewed Pat M asked,

258+分 已查看1 11,603+人的Pat M問,

I would like to track and update in this thread the latest best (and hopefully the simplest) method to bundle Angular (version 2, 4, …) for production on a live web server.

我想在此線程中跟蹤和更新最新的最佳(也是最簡單的)方法,以便將Angular(版本2、4…)捆綁在一起,以在實時Web服務器上進行生產。

Please include the Angular version within answers so we can track better when it moves to later releases.

請在答案中包括Angular版本,以便在移至更高版本時可以更好地進行跟蹤。

Nicolas Henneaux answered, (267+ points)

Nicolas Henneaux 回答了,(267分以上)

帶有Angular CLI的2.x, 4.x, 5.x (TypeScript) (2.x, 4.x, 5.x (TypeScript) with Angular CLI)

一次性設置 (OneTime Setup)

  • npm install -g @angular/cli

    npm install -g @angular/cli

  • ng new projectFolder creates a new application

    ng new projectFolder創建一個新的應用程序

捆綁步驟 (Bundling Step)

  • ng build --prod (run in command line when directory is projectFolder)

    ng build --prod (當目錄為projectFolder時在命令行中運行)

  • flag prod bundle for production (see the Angular documentation for the list of option included with the production flag).

    標記prod捆綁包(有關生產標記的選項列表,請參閱Angular文檔 )。

  • Compress using Brotli compression the resources using the following commandfor i in dist/*; do brotli $i; done

    使用Brotli壓縮 , for i in dist/*; do brotli $i; done使用以下命令壓縮資源for i in dist/*; do brotli $i; done for i in dist/*; do brotli $i; done

bundles are generated by default to projectFolder/dist/

捆綁包默認生成為projectFolder / dist /

輸出量 (Output)

Sizes with Angular 5.2.8 with CLI 1.7.2

帶有CLI 1.7.2 Angular 5.2.8大小

  • dist/main.[hash].bundle.js Your application bundled [ size: 151 KB for new Angular CLI application empty, 36 KB compressed].

    dist/main.[hash].bundle.js您的應用程序捆綁了[大小:151 KB,用于新的Angular CLI應用程序為空,壓縮為36 KB ]。

  • dist/polyfill.[hash].bundle.js the polyfill dependencies (@angular, RxJS...) bundled [ size: 58 KB for new Angular CLI application empty, 17 KB compressed].

    dist/polyfill.[hash].bundle.js捆綁了polyfill依賴項(@ angular,RxJS ...)[大小:58 KB,用于新的Angular CLI應用程序為空,壓縮為17 KB ]。

  • dist/index.html entry point of your application.

    應用程序的dist/index.html入口點。

  • dist/inline.[hash].bundle.js webpack loader

    dist/inline.[hash].bundle.js Webpack加載器

  • dist/style.[hash].bundle.css the style definitions

    dist/style.[hash].bundle.css樣式定義

  • dist/assets resources copied from the Angular CLI assets configuration

    從Angular CLI資產配置復制的dist/assets資源

部署方式 (Deployment)

You can get a preview of your application using the ng serve --prod command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200.

您可以使用ng serve --prod命令來啟動應用程序的預覽,該命令啟動本地HTTP服務器,以便可以使用http:// localhost:4200訪問帶有生產文件的應用程序。

For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.

對于生產用途,必須從您選擇的HTTP服務器中的dist文件夾中部署所有文件。

SourceTop

來源 頂部

BehaviorSubject與Observable? (BehaviorSubject vs Observable?)

250+ points ? 122,248+ viewed

250+分 已查看1 22,248+

250+ points ? 122,248+ viewed Kevin Mark asked,

250+分 1 22,248+瀏覽了Kevin Mark問,

I’m looking into Angular RxJs patterns and I don’t understand the difference between a BehaviorSubject and an Observable.

我正在研究Angular RxJs模式,但我不了解BehaviorSubject和Observable之間的區別。

From my understanding, a BehaviorSubject is a value that can change over time (can be subscribed to and subscribers can receive updated results). This seems to be the exact same purpose of an Observable.

據我了解,BehaviorSubject是一個隨時間變化的值(可以訂閱,訂閱者可以接收更新的結果)。 這似乎與Observable的目的完全相同。

When would you use an Observable vs a BehaviorSubject? Are there benefits to using a BehaviorSubject over an Observable or vice versa?

什么時候使用Observable與BehaviorSubject? 在Observable上使用BehaviorSubject有好處,反之亦然嗎?

Shantanu Bhadoria answered, (425+ points)

Shantanu Bhadoria 回答了,(425+分)

BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:

BehaviorSubject是主題的一種,主題是可觀察的特殊類型,因此您可以像其他任何可觀察對象一樣訂閱消息。 BehaviorSubject的獨特功能是:

  • It needs an initial value as it must always return a value on subscription even if it hasn’t received a next()

    它需要一個初始值,因為即使未收到next() ,它也必須始終在訂閱時返回一個值。

  • Upon subscription it returns the last value of the subject. A regular observable only triggers when it receives an onnext

    訂閱后,它將返回主題的最后一個值。 常規可觀察對象僅在收到onnext時觸發

  • at any point you can retrieve the last value of the subject in a non-observable code using the getValue() method.

    在任何時候,您都可以使用getValue()方法以不可觀察的代碼檢索主題的最后一個值。

Unique features of a subject compared to an observable are:

與可觀察對象相比,對象的獨特特征是:

  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.

    它不僅是可觀察者,而且是觀察者,因此您除了訂閱它之外,還可以將值發送給主題。

In addition you can get an observable from behavior subject using the asobservable() method on BehaviorSubject.

另外,您可以使用BehaviorSubject上的asobservable()方法從行為主體獲取可觀察對象。

Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.

Observable是泛型,而BehaviorSubject從技術上講是Observable的子類型,因為BehaviorSubject是具有特定質量的Observable。

Example with BehaviorSubject:

BehaviorSubject的示例:

// Behavior Subject// a is an initial value. if there is a subscription 
// after this, it would get "a" value immediately
let bSubject = new BehaviorSubject("a"); bSubject.next("b");bSubject.subscribe((value) => {console.log("Subscription got", value); // Subscription got b, // ^ This would not happen // for a generic observable // or generic subject by default
});bSubject.next("c"); // Subscription got c
bSubject.next("d"); // Subscription got d

Example 2 with regular subject:

例2包含常規主題:

// Regular Subjectlet subject = new Subject(); subject.next("b");subject.subscribe((value) => {console.log("Subscription got", value); // Subscription wont get // anything at this point
});subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d

An observable can be created from both Subject and BehaviorSubject using subject.asobservable(). Only difference being you can't send values to an observable using next() method.

可以使用subject.asobservable()從Subject和BehaviorSubject創建可觀察對象。 唯一的區別是您無法使用next()方法將值發送給可觀察對象。

In Angular services, I would use BehaviorSubject for a data service as a angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component’s subscription to this data.

在Angular服務中,我將對數據服務使用BehaviorSubject,因為有角度的服務通常在組件和行為主體確保使用該服務的組件接收到最后更新的數據之前就進行初始化,即使自組件訂閱該數據以來沒有新的更新也是如此。

SourceTop

來源 頂部

@Directive v / s @Component在Angular中 (@Directive v/s @Component in Angular)

239+ points ? 61,582+ viewed

239+分 查看了6 1,582+

239+ points ? 61,582+ viewed Prasanjit Dey asked,

239+分 6 1,582+瀏覽過的Prasanjit Dey 問,

What is the difference between @Component and @Directive in Angular? Both of them seem to do the same task and have the same attributes.

Angular中@Component@Directive什么區別? 他們兩個似乎完成相同的任務,并具有相同的屬性。

What are the use cases and when to prefer one over another?

用例是什么?何時優先使用一個?

jaker answered, (327+ points)

杰克 回答,(超過327分)

A @Component requires a view whereas a @Directive does not.

@Component需要視圖,而@Directive則不需要。

指令 (Directives)

I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

我將@Directive比作Angular 1.0指令,并帶有restrict: 'A'選項restrict: 'A' (指令不限于屬性用法。)指令將行為添加到現有DOM元素或現有組件實例中。 指令的一個示例用例是記錄對元素的單擊。

import {Directive} from '@angular/core';@Directive({selector: "[logOnClick]",hostListeners: {'click': 'onClick()',},
})class LogOnClick {constructor() {}onClick() { console.log('Element clicked!'); }
}

Which would be used like so:

可以這樣使用:

<button logOnClick>I log when clicked!<;/button>

組件 (Components)

A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component:

組件實際上是在創建自己的具有附加行為的視圖(DOM元素的層次結構),而不是添加/修改行為。 一個示例用例可能是聯系卡組件:

import {Component, View} from '@angular/core';@Component({selector: 'contact-card',template: `<div><h1>{{name}}</h1><p>{{city}}</p></div>`
})
class ContactCard {@Input() name: string@Input() city: stringconstructor() {}
}

Which would be used like so:

可以這樣使用:

<contact-card [name]="'foo'" [city]="'bar'"></contact-card>

ContactCard is a reusable UI component that we could use anywhere in our application, even within other components. These basically make up the UI building blocks of our applications.

ContactCard是可重用的UI組件,我們可以在應用程序中的任何位置使用它,甚至可以在其他組件中使用。 這些基本上構成了我們應用程序的UI構建塊。

綜上所述 (In summary)

Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

當您要創建具有自定義行為的UI的可重用的DOM元素集時,請編寫組件。 當您要編寫可重用的行為以補充現有DOM元素時,請編寫指令。

Sources:

資料來源:

  • @Directive documentation

    @Directive文檔

  • @Component documentation

    @Component文檔

  • Helpful blog post

    有用的博客文章

SourceTop

來源 頂部

帶有TypeScript錯誤http.get(…).map的角度HTTP GET不是[null]中的函數 (Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null])

233+ points ? 141,917+ viewed

233分以上 已查看1 41,917+

233+ points ? 141,917+ viewed Claudiu asked,

233分以上 Claudiu 問了 1 41,917+次觀看

I have a problem with HTTP in Angular.

我在Angular中遇到HTTP問題。

I just want to GET a JSON list and show it in the view.

我只想GET一個JSON列表并將其顯示在視圖中。

服務等級 (Service class)

import {Injectable} from "angular2/core";
import {Hall} from "./hall";
import {Http} from "angular2/http";
@Injectable()
export class HallService {public http:Http;public static PATH:string = 'app/backend/' constructor(http:Http) {this.http=http;}getHalls() {return this.http.get(HallService.PATH + 'hall.json').map((res:Response) => res.json());}
}

And in the HallListComponent I call the getHalls method from the service:

HallListComponent我從服務中調用getHalls方法:

export class HallListComponent implements OnInit {public halls:Hall[];public _selectedId:number;constructor(private _router:Router,private _routeParams:RouteParams,private _service:HallService) {this._selectedId = +_routeParams.get('id');}ngOnInit() {this._service.getHalls().subscribe((halls:Hall[])=>{ this.halls=halls;});}
}

However, I got an exception:

但是,我有一個例外:

TypeError: this.http.get(...).map is not a function in [null]

TypeError: this.http.get(...).map is not a function in [null]

霍爾中心組件 (hall-center.component)

import {Component} from "angular2/core";
import {RouterOutlet} from "angular2/router";
import {HallService} from "./hall.service";
import {RouteConfig} from "angular2/router";
import {HallListComponent} from "./hall-list.component";
import {HallDetailComponent} from "./hall-detail.component";
@Component({template:`<h2>my app</h2><router-outlet></router-outlet>`,directives: [RouterOutlet],providers: [HallService]
})@RouteConfig([{path: '/',         name: 'HallCenter', component:HallListComponent, useAsDefault:true},{path: '/hall-list', name: 'HallList', component:HallListComponent}
])export class HallCenterComponent{}

應用組件 (app.component)

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from "angular2/router";
import {RouteConfig} from "angular2/router";
import {HallCenterComponent} from "./hall/hall-center.component";
@Component({selector: 'my-app',template: `<h1>Examenopdracht Factory</h1><a [routerLink]="['HallCenter']">Hall overview</a><router-outlet></router-outlet>`,directives: [ROUTER_DIRECTIVES]
})@RouteConfig([{path: '/hall-center/...', name:'HallCenter',component:HallCenterComponent,useAsDefault:true}
])
export class AppComponent { }

tsconfig.json (tsconfig.json)

{"compilerOptions": {"target": "ES5","module": "system","moduleResolution": "node","sourceMap": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"removeComments": false,"noImplicitAny": false},"exclude": ["node_modules"]
}

Thierry Templier answered, (416+ points)

Thierry Templier 回答了,(416分以上)

I think that you need to import this:

我認為您需要導入以下內容:

import 'rxjs/add/operator/map'

Or more generally this if you want to have more methods for observables. WARNING: This will import all 50+ operators and add them to your application, thus affecting your bundle size and load times.

或更籠統地說,如果您想擁有更多可觀察的方法。 警告:這將導入所有50多個運算符,并將它們添加到您的應用程序中,從而影響捆綁包的大小和加載時間。

import 'rxjs/Rx';

See this issue for more details.

有關更多詳細信息,請參見此問題 。

SourceTop

來源 頂部

如何在Angular中使用jQuery? (How to use jQuery with Angular?)

233+ points ? 246,869+ viewed

233分以上 已查看2 46,869+

233+ points ? 246,869+ viewed Waog asked,

233分以上 2 46,869+瀏覽過Waog問,

Can anyone tell me, how to use jQuery with Angular?

誰能告訴我,如何在Angular中使用jQuery

class MyComponent {constructor() {// how to query the DOM element from here?}
}

I’m aware there are workarounds like manipulating the class or id of the DOM element upfront, but I’m hoping for a cleaner way of doing it.

我知道有一些變通方法,例如預先處理DOM元素的ID ,但我希望有一種更干凈的方法。

werenskjold answered, (258+ points)

Arenskjold 回答了,(258分以上)

Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.

與ng1相比,使用來自Angular2的jQuery輕而易舉。 如果您使用的是TypeScript,則可以先引用jQuery打字稿定義。

tsd install jquery --save
or
typings install dt~jquery --global --save

TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery

因為你可以只使用TypescriptDefinitions不需要any作為類型$jQuery

In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.

在您的角度組件中,您應該使用@ViewChild()引用模板中的DOM元素。初始化視圖之后,您可以使用此對象的nativeElement屬性并傳遞給jQuery。

Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.

$ (或jQuery )聲明為JQueryStatic將為您提供對jQuery的類型化引用。

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;@Component({selector: 'ng-chosen',template: `<select #selectElem><option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option></select><h4> {{selectedValue}}</h4>`
})
export class NgChosenComponent implements AfterViewInit {@ViewChild('selectElem') el:ElementRef;items = ['First', 'Second', 'Third'];selectedValue = 'Second';ngAfterViewInit() {$(this.el.nativeElement).chosen().on('change', (e, args) => {this.selectedValue = args.selected;});}
}bootstrap(NgChosenComponent);

This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview

該示例可在plunker上找到: http ://plnkr.co/edit/Nq9LnK?p=preview

tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file

tslint會抱怨chosen不是$的屬性,要解決此問題,您可以在自定義* .d.ts文件的JQuery接口中添加定義

interface JQuery {chosen(options?:any):JQuery;
}

SourceTop

來源 頂部

Angular EXCEPTION:沒有Http的提供程序 (Angular EXCEPTION: No provider for Http)

230+ points ? 142,976+ viewed

230+分 已查看1 42,976+

230+ points ? 142,976+ viewed daniel asked,

230+分 1 42976+觀看過的丹尼爾問,

I am getting the EXCEPTION: No provider for Http! in my Angular app. What am I doing wrong?

我正在得到EXCEPTION: No provider for Http! 在我的Angular應用中。 我究竟做錯了什么?

import {Http, Headers} from 'angular2/http';
import {Injectable} from 'angular2/core'@Component({selector: 'greetings-ac-app2',providers: [],templateUrl: 'app/greetings-ac2.html',directives: [NgFor, NgModel, NgIf, FORM_DIRECTIVES],pipes: []
})
export class GreetingsAcApp2 {private str:any;constructor(http: Http) {this.str = {str:'test'};http.post('http://localhost:18937/account/registeruiduser/',JSON.stringify(this.str),{headers: new Headers({'Content-Type': 'application/json'})});

Philip Miglinci answered, (381+ points)

Philip Miglinci 回答,(超過381分)

Import the HttpModule

導入HttpModule

import { HttpModule } from '@angular/http';@NgModule({imports: [ BrowserModule, HttpModule ],providers: [],declarations: [ AppComponent ],bootstrap: [ AppComponent ]
})
export default class AppModule { }platformBrowserDynamic().bootstrapModule(AppModule);

Ideally you split up this code in two separate files. For further information read:

理想情況下,您可以將此代碼分成兩個單獨的文件。 有關更多信息,請閱讀:

  • https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html

    https://angular.io/docs/ts/latest/cookbook/rc4-to-rc5.html

  • https://angular.io/docs/ts/latest/guide/ngmodule.html

    https://angular.io/docs/ts/latest/guide/ngmodule.html

SourceTop

來源 頂部

無法綁定到“ formGroup”,因為它不是“ form”的已知屬性 (Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’)

227+ points ? 127,130+ viewed

227+分 已查看1 27,130+

227+ points ? 127,130+ viewed johnnyfittizio asked,

227+分 觀看 1 27,130+次johnnyfittizio問,

THE SITUATION:

情況:

Please help! I am trying to make what should be a very simple form in my Angular2 app but no matter what it never works.

請幫忙! 我正在嘗試使Angular2應用程序中的表單變得非常簡單,但是不管它永遠無法工作。

ANGULAR VERSION:

角版本:

Angular 2.0.0 Rc5

角2.0.0 Rc5

THE ERROR:

錯誤:

Can't bind to 'formGroup' since it isn't a known property of 'form'

THE CODE:

代碼:

The view:

風景:

<form [formGroup]="newTaskForm" (submit)="createNewTask()"><div class="form-group"><label for="name">Name</label><input type="text" name="name" required></div><button type="submit" class="btn btn-default">Submit</button>
</form>

The controller:

控制器:

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder }  from '@angular/forms';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { Task } from './task';@Component({selector: 'task-add',templateUrl: 'app/task-add.component.html'})export class TaskAddComponent {newTaskForm: FormGroup;constructor(fb: FormBuilder) {this.newTaskForm = fb.group({name: ["", Validators.required]});}createNewTask(){console.log(this.newTaskForm.value)}}

The ngModule:

ngModule:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';import { routing }        from './app.routing';
import { AppComponent }  from './app.component';
import { TaskService } from './task.service'@NgModule({imports: [ BrowserModule,routing,FormsModule],declarations: [ AppComponent ],providers: [TaskService],bootstrap: [ AppComponent ]
})export class AppModule { }

THE QUESTION:

問題:

Why am I getting that error?

為什么會出現該錯誤?

Am I missing something?

我想念什么嗎?

Stefan Svrkota answered, (465+ points)

Stefan Svrkota 回答了,(465分以上)

RC5 FIX

RC5修復

You need to import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms' in your controller and add it to directives in @Component. That will fix the problem.

您需要import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'控制器中的import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'并將其添加到@Component directives中。 這樣可以解決問題。

After you fix that, you will probably get another error because you didn’t add formControlName="name" to your input in form.

解決此問題之后,您可能會遇到另一個錯誤,因為沒有將formControlName="name"添加到表單的輸入中。

RC6/RC7/Final release FIX

RC6 / RC7 /最終發行版FIX

To fix this error, you just need to import ReactiveFormsModule from @angular/forms in your module. Here's the example of a basic module with ReactiveFormsModule import:

要解決此錯誤,您只需要從模塊中的@angular/forms導入ReactiveFormsModule 。 這是帶有ReactiveFormsModule導入的基本模塊的示例:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent }  from './app.component';@NgModule({imports: [BrowserModule,FormsModule,ReactiveFormsModule],declarations: [AppComponent],bootstrap: [AppComponent]
})export class AppModule { }

To explain further, formGroup is a selector for directive named FormGroupDirective that is a part of ReactiveFormsModule, hence the need to import it. It is used to bind an existing FormGroup to a DOM element. You can read more about it on Angular's official docs page.

為了進一步說明, formGroup是名為FormGroupDirective指令的選擇器,該指令是ReactiveFormsModule的一部分,因此需要導入它。 它用于將現有的FormGroup綁定到DOM元素。 您可以在Angular的官方文檔頁面上了解有關它的更多信息。

SourceTop

來源 頂部

角度DI錯誤—例外:無法解析所有參數 (Angular DI Error — EXCEPTION: Can’t resolve all parameters)

221+ points ? 142,497+ viewed

221+分 已查看1 42,497+

221+ points ? 142,497+ viewed Keith Otto asked,

221+分 1 42497+觀看過Keith Otto的提問,

I’ve built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three other components I have created however.

我已經在Angular中構建了一個基本應用程序,但是遇到一個奇怪的問題,即我無法將服務注入我的組件之一。 但是,它可以很好地注入我創建的其他三個組件中的任何一個。

For starters, this is the service:

對于初學者,這是服務:

import { Injectable } from '@angular/core';@Injectable()
export class MobileService {screenWidth: number;screenHeight: number;constructor() {this.screenWidth = window.outerWidth;this.screenHeight = window.outerHeight;window.addEventListener("resize", this.onWindowResize.bind(this) )}onWindowResize(ev: Event) {var win = (ev.currentTarget as Window);this.screenWidth = win.outerWidth;this.screenHeight = win.outerHeight;}}

And the component that it refuses to work with:

以及它拒絕使用的組件:

import { Component, } from '@angular/core';
import { NgClass } from '@angular/common';
import { ROUTER_DIRECTIVES } from '@angular/router';import {MobileService} from '../';@Component({moduleId: module.id,selector: 'pm-header',templateUrl: 'header.component.html',styleUrls: ['header.component.css'],directives: [ROUTER_DIRECTIVES, NgClass],
})
export class HeaderComponent {mobileNav: boolean = false;constructor(public ms: MobileService) {console.log(ms);}}

The error I get in the browser console is this:

我在瀏覽器控制臺中遇到的錯誤是這樣的:

EXCEPTION: Can't resolve all parameters for HeaderComponent: (?).

EXCEPTION: Can't resolve all parameters for HeaderComponent: (?).

I have the service in the bootstrap function so it has a provider. And I seem to be able to inject it into the constructor of any of my other components without issue.

我在引導功能中具有該服務,因此它具有提供程序。 而且我似乎可以將其注入到其他任何組件的構造函數中,而不會出現問題。

Günter Z?chbauer answered, (272+ points)

GünterZ?chbauer 回答了,(272分以上)

Import it from the file where it is declared directly instead of the barrel.

從直接聲明的文件而不是桶中導入它。

I don’t know what exactly causes the issue but I saw it mentioned several times (probably some kind of circular dependency).

我不知道是什么導致問題的確切原因,但是我多次提到它(可能是某種循環依賴)。

It should also be fixable by changing the order of the exports in the barrel (don’t know details, but was mentioned as well)

還應該通過更改桶中出口的順序來固定(不知道細節,但也有人提到)

SourceTop

來源 頂部

Angular —為每個請求設置標題 (Angular — Set headers for every request)

209+ points ? 205,557+ viewed

209+分 已查看2 05,557+

209+ points ? 205,557+ viewed Avijit Gupta asked,

209+分 2 05,557+次瀏覽Avijit Gupta問,

I need to set some Authorization headers after the user has logged in, for every subsequent request.

對于每個后續請求,我需要在用戶登錄后設置一些Authorization標頭。

To set headers for a particular request,

要為特定請求設置標題,

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);// HTTP POST using these headers
this.http.post(url, data, {headers: headers
})
// do something with the response

Reference

參考

But it would be not be feasible to manually set request headers for every request in this way.

但是以這種方式為每個請求手動設置請求標頭是不可行的。

How do I set the headers set once the user has logged in, and also remove those headers on logout?

用戶登錄后如何設置標頭集,并在注銷時也刪除這些標頭?

Thierry Templier answered, (283+ points)

Thierry Templier 回答了,(超過283分)

To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

要回答這個問題,您是否可以提供包裝來自Angular的原始Http對象的服務。 如下所述。

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';@Injectable()
export class HttpClient {constructor(private http: Http) {}createAuthorizationHeader(headers: Headers) {headers.append('Authorization', 'Basic ' +btoa('username:password')); }get(url) {let headers = new Headers();this.createAuthorizationHeader(headers);return this.http.get(url, {headers: headers});}post(url, data) {let headers = new Headers();this.createAuthorizationHeader(headers);return this.http.post(url, data, {headers: headers});}
}

And instead of injecting the Http object you could inject this one (HttpClient).

而不是注入Http對象,您可以注入這個對象( HttpClient )。

import { HttpClient } from './http-client';export class MyComponent {// Notice we inject "our" HttpClient here, naming it Http so it's easierconstructor(http: HttpClient) {this.http = httpClient;}handleSomething() {this.http.post(url, data).subscribe(result => {// console.log( result );});}
}

I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

我也覺得這事可以采用多供應商的做Http通過提供擴展自己的類類Http一個...查看此鏈接: http://blog.thoughtram.io/angular2/2015/11/23/multi -providers-in-angular-2.html 。

SourceTop

來源 頂部

如何在Angular中使用* ngIf else? (How to use *ngIf else in Angular?)

205+ points ? 203,768+ viewed

205分以上 已查看2 03,768+

205+ points ? 203,768+ viewed kawli norman asked,

205分以上 2 03,768+瀏覽過kawli norman 問,

I’m using Angular and I want to use *ngIf else (available since version 4) in this example:

我正在使用Angular,并且我想在此示例中使用*ngIf else (自版本4起可用):

<div *ngIf="isValid">content here ...
</div><div *ngIf="!isValid">other content here...
</div>

How can I acheive the same behavior with ngIf else ?

如何使用ngIf else實現相同的行為?

Bougarfaoui El houcine answered, (384+ points)

Bougarfaoui El houcine 回答了,(384分以上)

Angular 4 and 5:

角度4和5

using else :

使用else

<div *ngIf="isValid;else other_content">content here ...
</div><ng-template #other_content>other content here...</ng-template>

you can also use then else :

您還可以使用then else

<div *ngIf="isValid;then content else other_content">here is ignored</div><ng-template #content>content here...</ng-template>
<ng-template #other_content>other content here...</ng-template>

or then alone :

then獨自:

<div *ngIf="isValid;then content"></div><ng-template #content>content here...</ng-template>

Demo :

演示:

Plunker

柱塞

Details:

細節:

<ng-template> : is Angular’s own implementation of the <template> tag which is according to MDN :

<ng-template> :是Angular自己根據MDN實現的<template>標簽的實現:

The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaS cript The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaS

SourceTop

來源 頂部

Angular沒有NameService提供程序 (Angular no provider for NameService)

196+ points ? 186,526+ viewed

196+分 已查看1 86,526+

196+ points ? 186,526+ viewed M.Svrcek asked,

196+分 觀看了1 86,526+次M.Svrcek的提問,

I’ve got problem with loading class into Angular component. I’m trying to solve for long time, even tried to add it to single file. What I have is:

我在將類加載到Angular組件時遇到問題。 我試圖解決很長時間,甚至試圖將其添加到單個文件中。 我所擁有的是:

Application.ts

應用程序

/// <reference path="../typings/angular2/angular2.d.ts" />import {Component,View,bootstrap,NgFor} from "angular2/angular2";
import {NameService} from "./services/NameService";@Component({selector:'my-app',injectables: [NameService]
})
@View({template:'<h1>Hi {{name}}</h1>' +'<p>Friends</p>' +'<ul>' +'   <li *ng-for="#name of names">{{name}}</li>' +'</ul>',directives:[NgFor]
})class MyAppComponent
{name:string;names:Array<string>;constructor(nameService:NameService){this.name = 'Michal';this.names = nameService.getNames();}
}
bootstrap(MyAppComponent);

services/NameService.ts

services / NameService.ts

export class NameService {names: Array<string>;constructor() {this.names = ["Alice", "Aarav", "Martín", "Shannon", "Ariana", "Kai"];}getNames(){return this.names;}
}

All the time I’m getting error message saying “No provider for NameService” …

我一直在收到錯誤消息,說“沒有NameService的提供者”……

Can someone help me spot that small issue with my code?

有人可以幫我找出我的代碼中的小問題嗎?

Klas Mellbourn answered, (309+ points)

Klas Mellbourn 回答了,(309分以上)

You have to use providers instead of injectables

您必須使用providers而不是injectables

@Component({selector: 'my-app',providers: [NameService]
})

Complete code sample here.

在此處完成代碼示例 。

SourceTop

來源 頂部

將選擇元素綁定到Angular中的對象 (Binding select element to object in Angular)

194+ points ? 197,048+ viewed

194+分 已查看1 97,048+

194+ points ? 197,048+ viewed RHarris asked,

194+分 已查看1 97,048+個RHarris的 問題,

I’m new to Angular and trying to get up to speed with the new way of doing things.

我是Angular的新手,并試圖跟上新的工作方式。

I’d like to bind a select element to a list of objects — which is easy enough:

我想將select元素綁定到對象列表-這很容易:

@Component({selector: 'myApp',template: `<h1>My Application</h1><select [(ngModel)]="selectedValue"><option *ngFor="#c of countries" value="c.id">{{c.name}}</option></select>`
})
export class AppComponent{countries = [{id: 1, name: "United States"},{id: 2, name: "Australia"}{id: 3, name: "Canada"}{id: 4, name: "Brazil"}{id: 5, name: "England"}];selectedValue = null;
}

In this case, it appears that selectedValue would be a number — the id of the selected item.

在這種情況下,似乎selectedValue將是一個數字-所選項目的ID。

However, I’d actually like to bind to the country object itself so that selectedValue is the object rather than just the id. I tried changing the value of the option like so:

但是,我實際上想綁定到country對象本身,以便selectedValue是對象,而不僅僅是id。 我試圖像這樣更改選項的值:

<option *ngFor="#c of countries" value="c">{{c.name}}<;/option>

but this does not seem to work. It seems to place an object in my selectedValue — but not the object that I’m expecting. You can see this in my Plunker example.

但這似乎不起作用。 似乎在我的selectedValue中放置了一個對象—但不是我期望的對象。 您可以在我的Plunker示例中看到這一點 。

I also tried binding to the change event so that I could set the object myself based on the selected id; however, it appears that the change event fires before the bound ngModel is updated — meaning I don’t have access to the newly selected value at that point.

我還嘗試綁定到change事件,以便可以根據所選的id自己設置對象; 但是,似乎更改事件在綁定的ngModel更新之前觸發-這意味著我當時無法訪問新選擇的值。

Is there a clean way to bind a select element to an object with Angular 2?

有沒有一種干凈的方法可以將選擇元素綁定到帶有Angular 2的對象?

Günter Z?chbauer answered, (361+ points)

GünterZ?chbauer 回答了,(361分以上)

<h1>My Application</h1>
<select [(ngModel)]="selectedValue"><option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>

Plunker example

柱塞示例

NOTE: you can use [ngValue]="c" instead of [ngValue]="c.id" where c is the complete country object.

注意:您可以使用[ngValue]="c"代替[ngValue]="c.id" ,其中c是完整的國家對象。

[value]="..." only supports string values[ngValue]="..." supports any type

[value]="..."僅支持字符串值[ngValue]="..."支持任何類型

update

更新

If the value is an object, the preselected instance needs to be identical with one of the values.

如果該value是一個對象,則預選實例必須與其中一個值相同。

See also the recently added custom comparison https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7

另請參閱自4.0.0-beta.7起可用的最近添加的自定義比較https://github.com/angular/angular/issues/13268

<select [compareWith]="compareFn" ...

Take care of if you want to access this within compareFn.

請注意是否要在compareFn訪問this

compareFn = this._compareFn.bind(this);// or 
// compareFn = (a, b) => this._compareFn(a, b);_comareFn((a, b) {if(this.x ...) {...
}

SourceTop

來源 頂部

NgModule中的聲明,提供程序和導入之間有什么區別 (What is difference between declarations, providers and import in NgModule)

188+ points ? 55,432+ viewed

188+分 已查看5 5,432+

188+ points ? 55,432+ viewed Ramesh Papaganti asked,

188+分 5 5,432+次查看Ramesh Papaganti 問,

I am trying to understand Angular (sometimes called Angular2+), then I came across @Module

我試圖了解Angular(有時稱為Angular2 +),然后遇到了@Module

  1. Imports

    進口貨
  2. Declarations

    聲明書
  3. Providers

    提供者

Following Angularjs-2 quick start

遵循Angularjs-2快速入門

Günter Z?chbauer answered, (277+ points)

GünterZ?chbauer 回答了,(277分以上)

Angular Concepts

角度概念

  • imports makes the exported declarations of other modules available in the current module

    imports使其他模塊的導出聲明在當前模塊中可用

  • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.

    declarations將使當前模塊中的指令(包括組件和管道)可用于當前模塊中的其他指令。 指令,組件或管道的選擇器只有在聲明或導入時才與HTML匹配。

  • providers are to make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as dependency.

    providers者應使DI知道服務和價值。 它們被添加到根范圍,并且被注入到其他具有它們依賴關系的服務或指令中。

A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

providers一種特殊情況是延遲加載的模塊,它們具有自己的子注入器。 providers延遲加載模塊的僅提供給默認此延遲加載模塊(未整個應用程序,因為它與其他模塊)。

For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html

有關模塊的更多詳細信息,另請參見https://angular.io/docs/ts/latest/guide/ngmodule.html

  • exports makes the components, directives, and pipes available in modules that add this module to imports. exports can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.

    exports使模塊中的組件,指令和管道可用,從而將該模塊添加到importsexports還可以用于重新導出諸如CommonModule和FormsModule之類的模塊,這通常是在共享模塊中完成的。

  • entryComponents registers components for offline compilation so that they can be used with ViewContainerRef.createComponent(). Components used in router configurations are added implicitly.

    entryComponents注冊用于脫機編譯的組件,以便它們可以與ViewContainerRef.createComponent()一起使用。 路由器配置中使用的組件是隱式添加的。

TypeScript (ES2015) imports

TypeScript(ES2015)導入

import ... from 'foo/bar' (which may resolve to an index.ts) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.

import ... from 'foo/bar' ( 可能解析為index.ts )用于TypeScript導入。 每當在另一個打字稿文件中聲明的打字稿文件中使用標識符時,都需要這些。

Angular’s @NgModule() imports and TypeScript import are entirely different concepts.

Angular的@NgModule() imports和TypeScript import完全不同的概念

See also jDriven — TypeScript and ES6 import syntax

另請參見jDriven — TypeScript和ES6導入語法

Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.

Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.

SourceTop

來源 頂部

在Angular中,如何確定活動路線? (In Angular, how do you determine the active route?)

187+ points ? 100,870+ viewed

187+分 已查看1 00,870+

187+ points ? 100,870+ viewed Michael Oryl asked,

187+分 1 00,870+瀏覽過Michael Oryl 問,

NOTE: There are many different answers here, and most have been valid at one time or another. The fact is that what works has changed a number of times as the Angular team has changed its Router. The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own. As of RC.3, the preferred solution is to use [routerLinkActive] as shown in this answer.

注意: 這里有很多不同的答案,大多數答案一次或一次都有效。 事實是,隨著Angular團隊更改了路由器,有效的方法已經改變了很多次。 最終將成為 Angular路由器的Router 3.0版本打破了許多解決方案,但提供了一個非常簡單的解決方案。 從RC.3開始,首選解決方案是使用[routerLinkActive] ,如本答案所示。

In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?

在Angular應用程序中(我撰寫本文時為2.0.0-beta.0版本中的當前版本),如何確定當前活動的路由是什么?

I’m working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output> tag.

我正在開發一個使用Bootstrap 4的應用程序,當在<router-outp ut>標簽中顯示其關聯組件時,我需要一種方法來將導航鏈接/按鈕標記為活動狀態。

I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn’t cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).

我意識到當單擊其中一個按鈕時,我可以自己維護狀態,但是這不會涉及將多條路徑放入同一條路線的情況(例如主導航菜單以及主組件中的本地菜單) )。

Any suggestions or links would be appreciated. Thanks.

任何建議或鏈接將不勝感激。 謝謝。

jessepinho answered, (229+ points)

jessepinho 回答,(超過229分)

With the new Angular router, you can add a [routerLinkActive]="['your-class-name']" attribute to all your links:

使用新的Angular路由器 ,您可以將[routerLinkActive]="['your-class-name']"屬性添加到所有鏈接:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>

Or the simplified non-array format if only one class is needed:

或者,如果只需要一個類,則為簡化的非數組格式:

<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>

See the poorly documented routerLinkActive directive for more info. (I mostly figured this out via trial-and-error.)

有關更多信息,請參見文檔文獻不routerLinkActive指令 。 (我主要是通過反復試驗弄清楚這一點。)

UPDATE: Better documentation for the routerLinkActive directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)

更新:現在可以在此處找到更好的關于routerLinkActive指令的文檔。 (感謝@Victor Hugo Arango A.在下面的評論中。)

SourceTop

來源 頂部

Angular CLI SASS選項 (Angular CLI SASS options)

187+ points ? 106,289+ viewed

187+分 已查看1 06,289+

187+ points ? 106,289+ viewed JDillon522 asked,

187+分 已查看1 06,289+則JDillon522 詢問,

I’m new to Angular and I’m coming from the Ember community. Trying to use the new Angular-CLI based off of Ember-CLI.

我是Angular的新手,我來自Ember社區。 嘗試使用基于Ember-CLI的新Angular-CLI。

I need to know the best way to handle SASS in a new Angular project. I tried using the ember-cli-sass repo to see if it would play along since a number of core components of the Angular-CLI are run off of Ember-CLI modules.

我需要知道在新的Angular項目中處理SASS的最佳方法。 我嘗試使用ember-cli-sass庫來查看它是否可以正常運行,因為Angular-CLI的許多核心組件都使用了Ember-CLI模塊。

It didnt work but than again not sure if I just misconfigured something.

它沒有用,但還是不確定我是否配置錯誤。

Also, what is the best way to organize styles in a new Angular project? It would be nice to have the sass file in the same folder as the component.

另外,在新的Angular項目中組織樣式的最佳方法是什么? 最好將sass文件與組件放在同一文件夾中。

Mertcan Diken answered, (323+ points)

Mertcan Diken 回答了,(323分以上)

When you are creating your project with angular cli try this:

當您使用angular cli創建項目時,請嘗試以下操作:

ng new My_New_Project --style=sass

This generating all your components with predifined sass files.

這將生成帶有預定義sass文件的所有組件。

If you want scss syntax create your project with :

如果要使用scss語法,請使用以下命令創建項目:

ng new My_New_Project --style=scss

If you are changing your existing style in your project

如果您要更改項目中的現有樣式

ng set defaults.styleExt scss

Cli handles the rest of it.

Cli處理其余的工作。

SourceTop

來源 頂部

Triggering change detection manually in Angular (Triggering change detection manually in Angular)

186+ points ? 102,556+ viewed

186+ points ? 1 02,556+ viewed

186+ points ? 102,556+ viewed jz87 asked,

186+ points ? 1 02,556+ viewed jz87 asked,

I’m writing an Angular component that has a property Mode(): string. I would like to be able to set this property programmatically not in response to any event. The problem is that in the absence of a browser event, a template binding {{Mode}} doesn't update. Is there a way to trigger this change detection manually?

I'm writing an Angular component that has a property Mode(): string . I would like to be able to set this property programmatically not in response to any event. The problem is that in the absence of a browser event, a template binding {{Mode}} doesn't update. Is there a way to trigger this change detection manually?

Mark Rajcok answered, (345+ points)

Mark Rajcok answered, (345+ points)

Try one of these:

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree

    ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- ie, check the full component tree

  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.

    NgZone.run(callback) - similar to $rootScope.$apply(callback) -- ie, evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.

  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

    ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- ie, check only this component and its children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

You can inject ApplicationRef , NgZone , or ChangeDetectorRef into your component.

SourceTop

Source Top

Angular and Typescript: Can't find names (Angular and Typescript: Can’t find names)

184+ points ? 181,472+ viewed

184+ points ? 1 81,472+ viewed

184+ points ? 181,472+ viewed user233232 asked,

184+ points ? 1 81,472+ viewed user233232 asked,

I am using Angular (version 2) with TypeScript (version 1.6) and when I compile the code I get these errors:

I am using Angular (version 2) with TypeScript (version 1.6) and when I compile the code I get these errors:

Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/change_detection/parser/locals.d.ts(4,42): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(1,25): Error TS2304: Cannot find name 'MapConstructor'.node_modules/angular2/src/core/facade/collection.d.ts(2,25): Error TS2304: Cannot find name 'SetConstructor'.node_modules/angular2/src/core/facade/collection.d.ts(4,27): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(4,39): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(7,9): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(8,30): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(11,43): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(12,27): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(14,23): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(15,25): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/collection.d.ts(94,41): Error TS2304: Cannot find name 'Set'.node_modules/angular2/src/core/facade/collection.d.ts(95,22): Error TS2304: Cannot find name 'Set'.node_modules/angular2/src/core/facade/collection.d.ts(96,25): Error TS2304: Cannot find name 'Set'.node_modules/angular2/src/core/facade/lang.d.ts(1,22): Error TS2304: Cannot find name 'BrowserNodeGlobal'.node_modules/angular2/src/core/facade/lang.d.ts(33,59): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/facade/promise.d.ts(1,10): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(3,14): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(8,32): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(9,38): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(10,35): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(10,93): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(11,34): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(12,32): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(12,149): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/facade/promise.d.ts(13,43): Error TS2304: Cannot find name 'Promise'.node_modules/angular2/src/core/linker/element_injector.d.ts(72,32): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/element_injector.d.ts(74,17): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/element_injector.d.ts(78,184): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/element_injector.d.ts(83,182): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/element_injector.d.ts(107,37): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/proto_view_factory.d.ts(27,146): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(52,144): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(76,79): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(77,73): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(94,31): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(97,18): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(100,24): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(103,142): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/linker/view.d.ts(104,160): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/render/api.d.ts(281,74): Error TS2304: Cannot find name 'Map'.node_modules/angular2/src/core/zone/ng_zone.d.ts(1,37): Error TS2304: Cannot find name 'Zone'.

This is the code:

這是代碼:

import 'reflect-metadata';
import {bootstrap, Component, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/core';
@Component({selector: 'my-app',template: '<input type="text" [(ng-model)]="title" /><h1>{{title}}</h1>',directives: [ CORE_DIRECTIVES ]
})
class AppComponent {title :string;constructor() {this.title = 'hello angular 2';}
}
bootstrap(AppComponent);

basarat answered, (50+ points)

basarat answered, (50+ points)

A known issue: https://github.com/angular/angular/issues/4902

A known issue: https://github.com/angular/angular/issues/4902

Core reason: the .d.ts file implicitly included by TypeScript varies with the compile target, so one needs to have more ambient declarations when targeting es5 even if things are actually present in the runtimes (e.g. chrome). More on lib.d.ts

Core reason: the .d.ts file implicitly included by TypeScript varies with the compile target, so one needs to have more ambient declarations when targeting es5 even if things are actually present in the runtimes (eg chrome). More on lib.d.ts

SourceTop

Source Top

Angular — What is the meanings of module.id in component? (Angular — What is the meanings of module.id in component?)

181+ points ? 54,337+ viewed

181+ points ? 5 4,337+ viewed

181+ points ? 54,337+ viewed Nishchit Dhanani asked,

181+ points ? 5 4,337+ viewed Nishchit Dhanani asked,

In an Angular app, I have seen that @Component has property moduleId. What does it mean?

In an Angular app, I have seen that @Component has property moduleId . 這是什么意思?

And when module.id is not defined anywhere, the app still works. How can it still work?

And when module.id is not defined anywhere, the app still works. How can it still work?

@Component({moduleId: module.id,selector: 'ng-app',templateUrl: 'app.component.html',styleUrls: ['app.component.css'],directives: [AppComponent]
});

Nishchit Dhanani answered, (145+ points)

Nishchit Dhanani answered, (145+ points)

The beta release of Angular (since vesion 2-alpha.51) supports relative assets for components, like templateUrl and styleUrls in the @Component decorator.

The beta release of Angular (since vesion 2-alpha.51) supports relative assets for components, like templateUrl and styleUrls in the @Component decorator.

module.id works when using CommonJS. You don't need to worry about how it works.

module.id works when using CommonJS. You don't need to worry about how it works.

Remember: setting moduleId: module.id in the @Component decorator is the key here. If you don't have that then Angular 2 will be looking for your files at the root level.

Remember : setting moduleId: module.id in the @Component decorator is the key here. If you don't have that then Angular 2 will be looking for your files at the root level.

Source from Justin Schwartzenberger’s post, thanks to @Pradeep Jain

Source from Justin Schwartzenberger's post , thanks to @Pradeep Jain

Update on 16 Sep 2016:

Update on 16 Sep 2016:

If you are using webpack for bundling then you don't need module.id in decorator. Webpack plugins auto handle (add it) module.id in final bundle

If you are using webpack for bundling then you don't need module.id in decorator. Webpack plugins auto handle (add it) module.id in final bundle

SourceTop

Source Top

How can I get new selection in “select” in Angular 2? (How can I get new selection in “select” in Angular 2?)

175+ points ? 203,064+ viewed

175+ points ? 2 03,064+ viewed

175+ points ? 203,064+ viewed Hongbo Miao asked,

175+ points ? 2 03,064+ viewed Hongbo Miao asked,

I am using Angular 2 (TypeScript).

I am using Angular 2 (TypeScript).

I want to do something for new selection, but what I got in onChange() is always last selection. How can I get new selection?

I want to do something for new selection, but what I got in onChange() is always last selection. How can I get new selection?

<select [(ngModel)]="selectedDevice" (change)="onChange($event)"><option *ngFor="#i of devices">{{i}}</option>
</select>onChange($event) {console.log(this.selectedDevice);// I want to do something here for new selectedDevice, but what I// got here is always last selection, not the one I just select.
}

Mark Rajcok answered, (370+ points)

Mark Rajcok answered, (370+ points)

If you don’t need two-way data-binding:

If you don't need two-way data-binding:

<select (change)="onChange($event.target.value)"><option *ngFor="let i of devices">{{i}}</option>
</select>onChange(deviceValue) {console.log(deviceValue);
}

For two-way data-binding, separate the event and property bindings:

For two-way data-binding, separate the event and property bindings:

<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2"><option [value]="i" *ngFor="let i of devices">{{i}}</option>
</select>export class AppComponent {devices = 'one two three'.split(' ');selectedDevice = 'two';onChange(newValue) {console.log(newValue);this.selectedDevice = newValue;// ... do other stuff here ...
}

If devices is array of objects, bind to ngValue instead of value:

If devices is array of objects, bind to ngValue instead of value :

<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3"><option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
{{selectedDeviceObj | json}}export class AppComponent {deviceObjects = [{name: 1}, {name: 2}, {name: 3}];selectedDeviceObj = this.deviceObjects[1];onChangeObj(newObj) {console.log(newObj);this.selectedDeviceObj = newObj;// ... do other stuff here ...}
}

Plunker — does not use <form>Plunker - uses <form> and uses the new forms API

Plunker — does not use <form> Plunker - uses <form> and uses the new forms API

SourceTop

Source Top

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property (Angular exception: Can’t bind to ‘ngForIn’ since it isn’t a known native property)

172+ points ? 48,252+ viewed

172+ points ? 4 8,252+ viewed

172+ points ? 48,252+ viewed Mark Rajcok asked,

172+ points ? 4 8,252+ viewed Mark Rajcok asked,

What am I doing wrong?

我究竟做錯了什么?

import {bootstrap, Component} from 'angular2/angular2'@Component({selector: 'conf-talks',template: `<div *ngFor="let talk in talks">{{talk.title}} by {{talk.speaker}}<p>{{talk.description}}</div>`
})
class ConfTalks {talks = [ {title: 't1', speaker: 'Brian', description: 'talk 1'},{title: 't2', speaker: 'Julie', description: 'talk 2'}];
}
@Component({selector: 'my-app',directives: [ConfTalks],template: '<conf-talks></conf-talks>'
})
class App {}
bootstrap(App, [])

The error is

The error is

EXCEPTION: Template parse errors:
Can't bind to 'ngForIn' since it isn't a known native property
("<div [ERROR ->]*ngFor="let talk in talks">

Mark Rajcok answered, (403+ points)

Mark Rajcok answered, (403+ points)

Since this is at least the third time I’ve wasted more than 5 min on this problem I figured I’d post the Q & A. I hope it helps someone else down the road… probably me!

Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road… probably me!

I typed in instead of of in the ngFor expression.

I typed in instead of of in the ngFor expression.

Befor 2-beta.17, it should be:

Befor 2-beta.17 , it should be:

<div *ngFor="#talk of talks">

As of beta.17, use the let syntax instead of #. See the UPDATE further down for more info.

As of beta.17, use the let syntax instead of # . See the UPDATE further down for more info.

Note that the ngFor syntax “desugars” into the following:

Note that the ngFor syntax “desugars” into the following:

<template ngFor #talk [ngForOf]="talks"><div>...</div>
</template>

If we use in instead, it turns into

If we use in instead, it turns into

<template ngFor #talk [ngForIn]="talks"><div>...</div>
</template>

Since ngForIn isn't an attribute directive with an input property of the same name (like ngIf), Angular then tries to see if it is a (known native) property of the template element, and it isn't, hence the error.

Since ngForIn isn't an attribute directive with an input property of the same name (like ngIf ), Angular then tries to see if it is a (known native) property of the template element, and it isn't, hence the error.

UPDATE — as of 2-beta.17, use the let syntax instead of #. This updates to the following:

UPDATE — as of 2-beta.17, use the let syntax instead of # . This updates to the following:

<div *ngFor="let talk of talks">

Note that the ngFor syntax “desugars” into the following:

Note that the ngFor syntax “desugars” into the following:

<template ngFor let-talk [ngForOf]="talks"><div>...</div>
</template>

If we use in instead, it turns into

If we use in instead, it turns into

<template ngFor let-talk [ngForIn]="talks"><div>...</div>
</template>

SourceTop

Source Top

*ngIf and *ngFor on same element causing error (*ngIf and *ngFor on same element causing error)

171+ points ? 85,728+ viewed

171+ points ? 8 5,728+ viewed

171+ points ? 85,728+ viewed garethdn asked,

171+ points ? 8 5,728+ viewed garethdn asked,

I’m having a problem with trying to use Angular’s *ngFor and *ngIf on the same element.

I'm having a problem with trying to use Angular's *ngFor and *ngIf on the same element.

When trying to loop through the collection in the *ngFor, the collection is seen as null and consequently fails when trying to access its properties in the template.

When trying to loop through the collection in the *ngFor , the collection is seen as null and consequently fails when trying to access its properties in the template.

@Component({selector: 'shell',template: `<h3>Shell</h3><button (click)="toggle()">Toggle!</button><div *ngIf="show" *ngFor="let thing of stuff">{{log(thing)}}<span>{{thing.name}}</span></div>`
})export class ShellComponent implements OnInit {public stuff:any[] = [];public show:boolean = false;constructor() {}ngOnInit() {this.stuff = [{ name: 'abc', id: 1 },{ name: 'huo', id: 2 },{ name: 'bar', id: 3 },{ name: 'foo', id: 4 },{ name: 'thing', id: 5 },{ name: 'other', id: 6 },]}toggle() {this.show = !this.show;}log(thing) {console.log(thing);}}

I know the easy solution is to move the *ngIf up a level but for scenarios like looping over list items in a ul, I'd end up with either an empty li if the collection is empty, or my lis wrapped in redundant container elements.

I know the easy solution is to move the *ngIf up a level but for scenarios like looping over list items in a ul , I'd end up with either an empty li if the collection is empty, or my li s wrapped in redundant container elements.

Example at this plnkr.

Example at this plnkr .

Note the console error:

Note the console error:

EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]

EXCEPTION: TypeError: Cannot read property 'name' of null in [{{thing.name}} in ShellComponent@5:12]

Am I doing something wrong or is this a bug?

Am I doing something wrong or is this a bug?

Günter Z?chbauer answered, (284+ points)

Günter Z?chbauer answered, (284+ points)

Angular2 doesn’t support more than one structural directive on the same element.As a workaround use the <ng-container> element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM.

Angular2 doesn't support more than one structural directive on the same element.As a workaround use the <ng-container> element that allows you to use separate elements for each structural directive, but it is not stamped to the DOM .

<ng-container *ngIf="show"><div *ngFor="let thing of stuff">{{log(thing)}}<span>{{thing.name}}</span></div>
</ng-container>

<ng-template> (<template> before Angular4) allows to do the same but with a different syntax which is confusing and no longer recommended

<ng-template> ( <template> before Angular4) allows to do the same but with a different syntax which is confusing and no longer recommended

<ng-template [ngIf]="show"><div *ngFor="let thing of stuff">{{log(thing)}}<span>{{thing.name}}</span></div>
</ng-template>

SourceTop

Source Top

What is the Angular equivalent to an AngularJS $watch? (What is the Angular equivalent to an AngularJS $watch?)

169+ points ? 95,029+ viewed

169+ points ? 9 5,029+ viewed

169+ points ? 95,029+ viewed Erwin asked,

169+ points ? 9 5,029+ viewed Erwin asked,

In AngularJS you were able to specify watchers to observe changes in scope variables using the $watch function of the $scope. What is the equivalent of watching for variable changes (in, for example, component variables) in Angular?

In AngularJS you were able to specify watchers to observe changes in scope variables using the $watch function of the $scope . What is the equivalent of watching for variable changes (in, for example, component variables) in Angular?

Mark Rajcok answered, (226+ points)

Mark Rajcok answered, (226+ points)

In Angular 2, change detection is automatic… $scope.$watch() and $scope.$digest() R.I.P.

In Angular 2, change detection is automatic… $scope.$watch() and $scope.$digest() RIP

Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section “The Other Stuff”).

Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section “The Other Stuff”).

Here’s my understanding of how change detection works:

Here's my understanding of how change detection works:

  • Zone.js “monkey patches the world” — it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use setTimeout() inside our components rather than something like $timeout... because setTimeout() is monkey patched.

    Zone.js “monkey patches the world” — it intercepts all of the asynchronous APIs in the browser (when Angular runs). This is why we can use setTimeout() inside our components rather than something like $timeout ... because setTimeout() is monkey patched.

  • Angular builds and maintains a tree of “change detectors”. There is one such change detector (class) per component/directive. (You can get access to this object by injecting ChangeDetectorRef.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches() that Angular 1 would set up for {{}} template bindings.

    Angular builds and maintains a tree of “change detectors”. There is one such change detector (class) per component/directive. (You can get access to this object by injecting ChangeDetectorRef .) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches() that Angular 1 would set up for {{}} template bindings.

    Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).

    Unlike Angular 1, the change detection graph is a directed tree and cannot have cycles (this makes Angular 2 much more performant, as we'll see below).

  • When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to — the shared application model/state and/or the component’s view state.

    When an event fires (inside the Angular zone), the code we wrote (the event handler callback) runs. It can update whatever data it wants to — the shared application model/state and/or the component's view state.
  • After that, because of the hooks Zone.js added, it then runs Angular’s change detection algorithm. By default (i.e., if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.

    After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (ie, if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.

  • Lifecycle hooks are called as part of change detection.

    Lifecycle hooks are called as part of change detection.

    If the component data you want to watch is a primitive input property (String, boolean, number), you can implement

    If the component data you want to watch is a primitive input property (String, boolean, number), you can implement

    ngOnChanges() to be notified of changes.

    ngOnChanges() to be notified of changes.

    If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement

    If the input property is a reference type (object, array, etc.), but the reference didn't change (eg, you added an item to an existing array), you'll need to implement

    ngDoCheck() (see this SO answer for more on this).

    ngDoCheck() (see this SO answer for more on this).

    You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's

    You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- ie, unidirectional data flow). 這是

    a plunker that violates that. Stateful pipes can also trip you up here.

    a plunker that violates that. Stateful pipes can also trip you up here.

  • For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.

    For any binding changes that are found, the Components are updated, and then the DOM is updated. Change detection is now finished.
  • The browser notices the DOM changes and updates the screen.

    The browser notices the DOM changes and updates the screen.

Other references to learn more:

Other references to learn more:

  • Angular’s $digest is reborn in the newer version of Angular — explains how the ideas from AngularJS are mapped to Angular

    Angular's $digest is reborn in the newer version of Angular — explains how the ideas from AngularJS are mapped to Angular

  • Everything you need to know about change detection in Angular — explains in great detail how change detection works under the hood

    Everything you need to know about change detection in Angular — explains in great detail how change detection works under the hood

  • Change Detection Explained — Thoughtram blog Feb 22, 2016 — probably the best reference out there

    Change Detection Explained — Thoughtram blog Feb 22, 2016 — probably the best reference out there

  • Savkin’s Change Detection Reinvented video — definitely watch this one

    Savkin's Change Detection Reinvented video — definitely watch this one

  • How does Angular 2 Change Detection Really Work?- jhade’s blog Feb 24, 2016

    How does Angular 2 Change Detection Really Work? - jhade's blog Feb 24, 2016

  • Brian’s video and Mi?ko’s video about Zone.js. Brian’s is about Zone.js. Mi?ko’s is about how Angular 2 uses Zone.js to implement change detection. He also talks about change detection in general, and a little bit about onPush.

    Brian's video and Mi?ko's video about Zone.js. Brian's is about Zone.js. Mi?ko's is about how Angular 2 uses Zone.js to implement change detection. He also talks about change detection in general, and a little bit about onPush .

  • Victor Savkins blog posts: Change Detection in Angular 2, Two phases of Angular 2 applications, Angular, Immutability and Encapsulation. He covers a lot of ground quickly, but he can be terse at times, and you’re left scratching your head, wondering about the missing pieces.

    Victor Savkins blog posts: Change Detection in Angular 2 , Two phases of Angular 2 applications , Angular, Immutability and Encapsulation . He covers a lot of ground quickly, but he can be terse at times, and you're left scratching your head, wondering about the missing pieces.

  • Ultra Fast Change Detection (Google doc) — very technical, very terse, but it describes/sketches the ChangeDetection classes that get built as part of the tree

    Ultra Fast Change Detection (Google doc) — very technical, very terse, but it describes/sketches the ChangeDetection classes that get built as part of the tree

SourceTop

Source Top

Importing lodash into angular2 + typescript application (Importing lodash into angular2 + typescript application)

167+ points ? 104,431+ viewed

167+ points ? 1 04,431+ viewed

167+ points ? 104,431+ viewed Davy asked,

167+ points ? 1 04,431+ viewed Davy asked,

I am having a hard time trying to get the lodash modules imported. I’ve setup my project using npm+gulp, and keep hitting the same wall. I’ve tried the regular lodash, but also lodash-es.

I am having a hard time trying to get the lodash modules imported. I've setup my project using npm+gulp, and keep hitting the same wall. I've tried the regular lodash, but also lodash-es.

The lodash npm package: (has an index.js file in the package root folder)

The lodash npm package: (has an index.js file in the package root folder)

import * as _ from 'lodash';

Results in:

Results in:

error TS2307: Cannot find module 'lodash'.

The lodash-es npm package: (has a defaut export in lodash.js i the package root folder)

The lodash-es npm package: (has a defaut export in lodash.js i the package root folder)

import * as _ from 'lodash-es/lodash';

Results in:

Results in:

error TS2307: Cannot find module 'lodash-es'.

Both the gulp task and webstorm report the same issue.

Both the gulp task and webstorm report the same issue.

Funny fact, this returns no error:

Funny fact, this returns no error:

import 'lodash-es/lodash';

… but of course there is no “_” …

… but of course there is no “_” …

My tsconfig.json file:

My tsconfig.json file:

{"compilerOptions": {"target": "es5","module": "system","moduleResolution": "node","sourceMap": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"removeComments": false,"noImplicitAny": false},"exclude": ["node_modules"]
}

My gulpfile.js:

My gulpfile.js:

var gulp = require('gulp'),ts = require('gulp-typescript'),uglify = require('gulp-uglify'),sourcemaps = require('gulp-sourcemaps'),tsPath = 'app/**/*.ts';gulp.task('ts', function () {var tscConfig = require('./tsconfig.json');gulp.src([tsPath]).pipe(sourcemaps.init()).pipe(ts(tscConfig.compilerOptions)).pipe(sourcemaps.write('./../js'));
});gulp.task('watch', function() {gulp.watch([tsPath], ['ts']);
});gulp.task('default', ['ts', 'watch']);

If i understand correctly, moduleResolution:’node’ in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I’ve also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?

If i understand correctly, moduleResolution:'node' in my tsconfig should point the import statements to the node_modules folder, where lodash and lodash-es are installed. I've also tried lots of different ways to import: absolute paths, relative paths, but nothing seems to work. Any ideas?

If necessary i can provide a small zip file to illustrate the problem.

If necessary i can provide a small zip file to illustrate the problem.

Taytay answered, (293+ points)

Taytay answered, (293+ points)

Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):

Here is how to do this as of Typescript 2.0: (tsd and typings are being deprecated in favor of the following):

$ npm install --save lodash# This is the new bit here: 
$ npm install --save @types/lodash

Then, in your .ts file:

Then, in your .ts file:

Either:

Either:

import * as _ from "lodash";

Or (as suggested by @Naitik):

Or (as suggested by @Naitik):

import _ from "lodash";

I’m not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn’t work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV.

I'm not positive what the difference is. We use and prefer the first syntax. However, some report that the first syntax doesn't work for them, and someone else has commented that the latter syntax is incompatible with lazy loaded webpack modules. YMMV。

Edit on Feb 27th, 2017:

Edit on Feb 27th, 2017:

According to @Koert below, import * as _ from "lodash"; is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".

According to @Koert below, import * as _ from "lodash"; is the only working syntax as of Typescript 2.2.1, lodash 4.17.4, and @types/lodash 4.14.53. He says that the other suggested import syntax gives the error "has no default export".

SourceTop

Source Top

How to detect a route change in Angular? (How to detect a route change in Angular?)

160+ points ? 108,593+ viewed

160+ points ? 1 08,593+ viewed

160+ points ? 108,593+ viewed AngularM asked,

160+ points ? 1 08,593+ viewed AngularM asked,

I am looking to detect a route change in my AppComponent.

I am looking to detect a route change in my AppComponent .

Thereafter I will check the global user token to see if he is logged in. Then I can redirect the user if he is not logged in.

Thereafter I will check the global user token to see if he is logged in. Then I can redirect the user if he is not logged in.

Ludohen answered, (223+ points)

Ludohen answered, (223+ points)

In Angular 2 you can subscribe (Rx event) to a Router instance. So you can do things like

In Angular 2 you can subscribe (Rx event) to a Router instance. So you can do things like

class MyClass {constructor(private router: Router) {router.subscribe((val) => /*whatever*/)}
}

Edit (since rc.1)

Edit (since rc.1)

class MyClass {constructor(private router: Router) {router.changes.subscribe((val) => /*whatever*/)}
}

Edit 2 (since 2.0.0)

Edit 2 (since 2.0.0)

see also : Router.events doc

see also : Router.events doc

class MyClass {constructor(private router: Router) {router.events.subscribe((val) => {// see also console.log(val instanceof NavigationEnd) });}
}

SourceTop

Source Top

Global Events in Angular (Global Events in Angular)

157+ points ? 83,980+ viewed

157+ points ? 8 3,980+ viewed

157+ points ? 83,980+ viewed skovmand asked,

157+ points ? 8 3,980+ viewed skovmand asked,

Is there no equivalent to $scope.emit() or $scope.broadcast() in Angular?

Is there no equivalent to $scope.emit() or $scope.broadcast() in Angular?

I know the EventEmitter functionality, but as far as I understand that will just emit an event to the parent HTML element.

I know the EventEmitter functionality, but as far as I understand that will just emit an event to the parent HTML element.

What if I need to communicate between fx. siblings or between a component in the root of the DOM and an element nested several levels deep?

What if I need to communicate between fx. siblings or between a component in the root of the DOM and an element nested several levels deep?

pixelbits answered, (304+ points)

pixelbits answered, (304+ points)

There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.

There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.

In Angular, there are other alternatives which I’ll try to explain below.

In Angular, there are other alternatives which I'll try to explain below.

@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component’s change detector strategy is to propagate all changes to an application model for all bindings from any connected component.

@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.

Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component’s template.

Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.

To answer your questions:

To answer your questions:

What if I need to communicate between sibling components?

What if I need to communicate between sibling components?

  1. Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.

    Shared Application Model : Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.

  2. Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it’s own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.

    Component Events : Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.

  3. Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.

    Service Events : Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. 在下面的更多內容。

How can I communicate between a Root component and a component nested several levels deep?

How can I communicate between a Root component and a component nested several levels deep?

  1. Shared Application Model: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.

    Shared Application Model : The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.

  2. Service Events: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1. The next section describes this idea in more detail.

    Service Events : You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1. The next section describes this idea in more detail.

Example of an Observable Service that uses Service Events to Propagate Changes

Example of an Observable Service that uses Service Events to Propagate Changes

Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.

Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.

export class TodoItem {constructor(public name: string, public done: boolean) {}
}
export class TodoService {public itemAdded$: EventEmitter<TodoItem>;private todoList: TodoItem[] = [];constructor() {this.itemAdded$ = new EventEmitter();}public list(): TodoItem[] {return this.todoList;}public add(item: TodoItem): void {this.todoList.push(item);this.itemAdded$.emit(item);}
}

Here is how a root component would subscribe to the event:

Here is how a root component would subscribe to the event:

export class RootComponent {private addedItem: TodoItem;constructor(todoService: TodoService) {todoService.itemAdded$.subscribe(item => this.onItemAdded(item));}private onItemAdded(item: TodoItem): void {// do something with added itemthis.addedItem = item;}
}

A child component nested several levels deep would subscribe to the event in the same way:

A child component nested several levels deep would subscribe to the event in the same way:

export class GrandChildComponent {private addedItem: TodoItem;constructor(todoService: TodoService) {todoService.itemAdded$.subscribe(item => this.onItemAdded(item));}private onItemAdded(item: TodoItem): void {// do something with added itemthis.addedItem = item;}
}

Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):

Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):

@Component({selector: 'todo-list',template: `<ul><li *ngFor="#item of model"> {{ item.name }}</li></ul><br />Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>`
})
export class TriggeringComponent{private model: TodoItem[];constructor(private todoService: TodoService) {this.model = todoService.list();}add(value: string) {this.todoService.add(new TodoItem(value, false));}
}

Reference: Change Detection in Angular

Reference: Change Detection in Angular

SourceTop

Source Top

What are differences between SystemJS and Webpack? (What are differences between SystemJS and Webpack?)

155+ points ? 60,183+ viewed

155+ points ? 6 0,183+ viewed

155+ points ? 60,183+ viewed smartmouse asked,

155+ points ? 6 0,183+ viewed smartmouse asked,

I’m creating my first Angular application and I would figure out what is the role of the module loaders. Why we need them? I tried to search and search on Google and I can’t understand why we need to install one of them to run our application?

I'm creating my first Angular application and I would figure out what is the role of the module loaders. Why we need them? I tried to search and search on Google and I can't understand why we need to install one of them to run our application?

Couldn’t it be enough to just use import to load stuff from node modules?

Couldn't it be enough to just use import to load stuff from node modules?

I have followed this tutorial (that uses SystemJS) and it makes me to use systemjs.config.js file:

I have followed this tutorial (that uses SystemJS) and it makes me to use systemjs.config.js file:

/*** System configuration for Angular samples* Adjust as necessary for your application needs.*/
(function(global) {// map tells the System loader where to look for thingsvar map = {'app':                        'transpiled', // 'dist','@angular':                   'node_modules/@angular','angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api','rxjs':                       'node_modules/rxjs'};// packages tells the System loader how to load when no filename and/or no extensionvar packages = {'app':                        { main: 'main.js',  defaultExtension: 'js' },'rxjs':                       { defaultExtension: 'js' },'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },};var ngPackageNames = ['common','compiler','core','forms','http','platform-browser','platform-browser-dynamic','router','router-deprecated','upgrade',];// Individual files (~300 requests):function packIndex(pkgName) {packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };}// Bundled (~40 requests):function packUmd(pkgName) {packages['@angular/'+pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };}// Most environments should use UMD; some (Karma) need the individual index filesvar setPackageConfig = System.packageWithIndex ? packIndex : packUmd;// Add package entries for angular packagesngPackageNames.forEach(setPackageConfig);var config = {map: map,packages: packages};System.config(config);
})(this);

Why we need this configuration file?Why we need SystemJS (or WebPack or others)?Finally, in your opinion what is the better?

Why we need this configuration file?Why we need SystemJS (or WebPack or others)?Finally, in your opinion what is the better?

Thierry Templier answered, (97+ points)

Thierry Templier answered, (97+ points)

If you go to the SystemJS Github page, you will see the description of the tool:

If you go to the SystemJS Github page, you will see the description of the tool:

Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.

Universal dynamic module loader - loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.

Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the systemjs.config.js allows us to configure the way in which module names are matched with their corresponding files.

Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the systemjs.config.js allows us to configure the way in which module names are matched with their corresponding files.

This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:

This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:

<script>System.import('app').catch(function(err){ console.error(err); });
</script>

When using TypeScript, and configuring the compiler to the commonjs module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:

When using TypeScript, and configuring the compiler to the commonjs module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:

{"compilerOptions": {"target": "es5","module": "commonjs", // <------"moduleResolution": "node","sourceMap": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"removeComments": false,"noImplicitAny": false}
}

Webpack is a flexible module bundler. This means that it goes further and doesn’t only handle modules but also provides a way to package your application (concat files, uglify files, …). It also provides a dev server with load reload for development

Webpack is a flexible module bundler. This means that it goes further and doesn't only handle modules but also provides a way to package your application (concat files, uglify files, …). It also provides a dev server with load reload for development

SystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.

SystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.

SourceTop

Source Top

Angular: Can't find Promise, Map, Set and Iterator (Angular: Can’t find Promise, Map, Set and Iterator)

154+ points ? 90,201+ viewed

154+ points ? 9 0,201+ viewed

154+ points ? 90,201+ viewed Stav Alfi asked,

154+ points ? 9 0,201+ viewed Stav Alfi asked,

After installing Angular, the Typescript compiler keep getting some errors about not finding Promise, Map, Set and Iterator.

After installing Angular, the Typescript compiler keep getting some errors about not finding Promise , Map , Set and Iterator .

Until now I ignored them but now I need Promise so my code can work.

Until now I ignored them but now I need Promise so my code can work.

import {Component} from 'angular2/core';
@Component({selector: 'greeting-cmp',template: `<div>{{ asyncGreeting | async}}</div>`
})
export class GreetingCmp {asyncGreeting: Promise<string> = new Promise(resolve => {
// after 1 second, the promise will resolvewindow.setTimeout(() => resolve('hello'), 1000);});
}Additional information:
npm -v is 2.14.12
node -v is v4.3.1
typescript v is 1.6

The errors:

The errors:

................ERROS OF MY CODE.................C:\Users\armyTik\Desktop\angular2\greeting_cmp.tsError:(7, 20) TS2304: Cannot find name 'Promise'.Error:(7, 42) TS2304: Cannot find name 'Promise'..........................................C:\Users\armyTik\Desktop\angular2\node_modules\angular2\platform\browser.d.tsError:(77, 90) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\application_ref.d.tsError:(83, 60) TS2304: Cannot find name 'Promise'.Error:(83, 146) TS2304: Cannot find name 'Promise'.Error:(96, 51) TS2304: Cannot find name 'Promise'.Error:(96, 147) TS2304: Cannot find name 'Promise'.Error:(133, 90) TS2304: Cannot find name 'Promise'.Error:(171, 81) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\change_detection\parser\locals.d.tsError:(3, 14) TS2304: Cannot find name 'Map'.Error:(4, 42) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\debug\debug_node.d.tsError:(14, 13) TS2304: Cannot find name 'Map'.Error:(24, 17) TS2304: Cannot find name 'Map'.Error:(25, 17) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\di\provider.d.tsError:(436, 103) TS2304: Cannot find name 'Map'.Error:(436, 135) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\compiler.d.tsError:(12, 50) TS2304: Cannot find name 'Promise'.Error:(16, 41) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\dynamic_component_loader.d.tsError:(108, 136) TS2304: Cannot find name 'Promise'.Error:(156, 150) TS2304: Cannot find name 'Promise'.Error:(197, 128) TS2304: Cannot find name 'Promise'.Error:(203, 127) TS2304: Cannot find name 'Promise'.Error:(204, 141) TS2304: Cannot find name 'Promise'.Error:(205, 119) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\render\api.d.tsError:(13, 13) TS2304: Cannot find name 'Map'.Error:(14, 84) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\async.d.tsError:(27, 33) TS2304: Cannot find name 'Promise'.Error:(28, 45) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\collection.d.tsError:(1, 25) TS2304: Cannot find name 'MapConstructor'.Error:(2, 25) TS2304: Cannot find name 'SetConstructor'.Error:(4, 27) TS2304: Cannot find name 'Map'.Error:(4, 39) TS2304: Cannot find name 'Map'.Error:(7, 9) TS2304: Cannot find name 'Map'.Error:(8, 30) TS2304: Cannot find name 'Map'.Error:(11, 43) TS2304: Cannot find name 'Map'.Error:(12, 27) TS2304: Cannot find name 'Map'.Error:(14, 23) TS2304: Cannot find name 'Map'.Error:(15, 25) TS2304: Cannot find name 'Map'.Error:(95, 41) TS2304: Cannot find name 'Set'.Error:(96, 22) TS2304: Cannot find name 'Set'.Error:(97, 25) TS2304: Cannot find name 'Set'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\lang.d.tsError:(13, 17) TS2304: Cannot find name 'Map'.Error:(14, 17) TS2304: Cannot find name 'Set'.Error:(78, 59) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\promise.d.tsError:(2, 14) TS2304: Cannot find name 'Promise'.Error:(7, 32) TS2304: Cannot find name 'Promise'.Error:(8, 38) TS2304: Cannot find name 'Promise'.Error:(9, 35) TS2304: Cannot find name 'Promise'.Error:(9, 93) TS2304: Cannot find name 'Promise'.Error:(10, 34) TS2304: Cannot find name 'Promise'.Error:(11, 32) TS2304: Cannot find name 'Promise'.Error:(11, 149) TS2304: Cannot find name 'Promise'.Error:(12, 43) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\headers.d.tsError:(43, 59) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\url_search_params.d.tsError:(11, 16) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\browser\browser_adapter.d.tsError:(75, 33) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\dom\dom_adapter.d.tsError:(85, 42) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\CoreOperators.d.tsError:(35, 67) TS2304: Cannot find name 'Promise'.Error:(50, 66) TS2304: Cannot find name 'Promise'.Error:(89, 67) TS2304: Cannot find name 'Promise'.Error:(94, 38) TS2304: Cannot find name 'Promise'.Error:(94, 50) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\Observable.d.tsError:(46, 62) TS2304: Cannot find name 'Promise'.Error:(47, 42) TS2304: Cannot find name 'Iterator'.Error:(103, 74) TS2304: Cannot find name 'Promise'.Error:(103, 84) TS2304: Cannot find name 'Promise'.Error:(143, 66) TS2304: Cannot find name 'Promise'.Error:(158, 65) TS2304: Cannot find name 'Promise'.Error:(201, 66) TS2304: Cannot find name 'Promise'.Error:(206, 38) TS2304: Cannot find name 'Promise'.Error:(206, 50) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\ForkJoinObservable.d.tsError:(6, 50) TS2304: Cannot find name 'Promise'.Error:(7, 58) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\FromObservable.d.tsError:(7, 38) TS2304: Cannot find name 'Promise'.Error:(7, 51) TS2304: Cannot find name 'Iterator'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\PromiseObservable.d.tsError:(9, 31) TS2304: Cannot find name 'Promise'.Error:(10, 26) TS2304: Cannot find name 'Promise'.

Kris Hollenbeck answered, (162+ points)

Kris Hollenbeck answered, (162+ points)

Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0 (Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0)

Updated 9/19/2016

Updated 9/19/2016

To get this to work with typescript 2.0.0, I did the following.

To get this to work with typescript 2.0.0, I did the following.

npm install --save-dev @types/core-js

npm install --save-dev @types/core-js

tsconfig.json

tsconfig.json

"compilerOptions": {"declaration": false,"emitDecoratorMetadata": true,"experimentalDecorators": true,"mapRoot": "./","module": "es6","moduleResolution": "node","noEmitOnError": true,"noImplicitAny": false,"outDir": "../dist/out-tsc","sourceMap": true,"target": "es5","typeRoots": ["../node_modules/@types"],"types": ["core-js"]}

More about @types with typescript 2.0.0.

More about @types with typescript 2.0.0.

  1. https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

    https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

  2. https://www.npmjs.com/~types

    https://www.npmjs.com/~types

Install Example:

Install Example:

npm install --save-dev @types/core-js

Duplicate Identifier errors

Duplicate Identifier errors

This is most likely because duplicate ecmascript 6 typings are already being imported from somewhere else most likely an old es6-shim.

This is most likely because duplicate ecmascript 6 typings are already being imported from somewhere else most likely an old es6-shim.

Double check typings.d.ts make sure there are no references to es6. Remove any reference to es6 from your typings directory if you have one.

Double check typings.d.ts make sure there are no references to es6 . Remove any reference to es6 from your typings directory if you have one.

For Example:

For Example:

This will conflict with types:['core-js'] in typings.json.

This will conflict with types:['core-js'] in typings.json.

{"globalDependencies": {"core-js": "registry:dt/core-js#0.0.0+20160602141332" // es6-shim will also conflict}
}

Including core-js in the types array in tsconfig.json should be the only place it is imported from.

Including core-js in the types array in tsconfig.json should be the only place it is imported from.

Angular CLI 1.0.0-beta.30

Angular CLI 1.0.0-beta.30

If you are using the Angular-CLI, remove the lib array in typings.json. This seems to conflict with declaring core-js in types.

If you are using the Angular-CLI, remove the lib array in typings.json . This seems to conflict with declaring core-js in types.

"compilerOptions" : {...// removed "lib": ["es6", dom"],...
},
"types" : ["core-js"]

Webstorm/Intellij Users using the Angular CLI

Webstorm/Intellij Users using the Angular CLI

Make sure the built in typescript compiler is disabled. This will conflict with the CLI. To compile your typescript with the CLI you can setup a ng serve configuration.

Make sure the built in typescript compiler is disabled. This will conflict with the CLI. To compile your typescript with the CLI you can setup a ng serve configuration.

Tsconfig compilerOptions lib vs types

Tsconfig compilerOptions lib vs types

If you prefer not to install core js type definitions there are some es6 libraries that come included with typescript. Those are used via the lib: [] property in tsconfig.

If you prefer not to install core js type definitions there are some es6 libraries that come included with typescript. Those are used via the lib: [] property in tsconfig.

See here for example: https://www.typescriptlang.org/docs/handbook/compiler-options.html

See here for example: https://www.typescriptlang.org/docs/handbook/compiler-options.html

Note: If --lib is not specified a default library is injected. The default library injected is: ? For --target ES5: DOM,ES5,ScriptHost ? For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

Note: If --lib is not specified a default library is injected. The default library injected is: ? For --target ES5: DOM,ES5,ScriptHost ? For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

tl;dr

tl;dr

Short answer either "lib": [ "es6", "dom" ] or "types": ["core-js"] can be used to resolve can't find Promise,Map, Set and Iterator. Using both however will cause duplicate identifier errors.

Short answer either "lib": [ "es6", "dom" ] or "types": ["core-js"] can be used to resolve can't find Promise,Map, Set and Iterator . Using both however will cause duplicate identifier errors.

SourceTop

Source Top

How to detect when an @Input() value changes in Angular? (How to detect when an @Input() value changes in Angular?)

154+ points ? 89,893+ viewed

154+ points ? 8 9,893+ viewed

154+ points ? 89,893+ viewed Jon Catmull asked,

154+ points ? 8 9,893+ viewed Jon Catmull asked,

I have a parent component (CategoryComponent), a child component (videoListComponent) and an ApiService.

I have a parent component ( CategoryComponent ), a child component ( videoListComponent ) and an ApiService.

I have most of this working fine i.e. each component can access the json api and get its relevant data via observables.

I have most of this working fine ie each component can access the json api and get its relevant data via observables.

Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via @Input().

Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via @Input() .

CategoryComponent.html

CategoryComponent.html

<video-list *ngIf="category" [categoryId]="category.id"></video-list>

This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via @Input() but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).

This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via @Input() but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).

In AngularJS I would have done a $watch on the variable. What is the best way to handle this?

In AngularJS I would have done a $watch on the variable. What is the best way to handle this?

Alan C. S. answered, (181+ points)

Alan CS answered, (181+ points)

Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :

Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :

  1. You can use the ngOnChanges() lifecycle method as also mentioned in older answers:

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers:

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers: @Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers: @Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }

  2. Documentation Links: ngOnChanges, SimpleChanges, SimpleChange

    Documentation Links: ngOnChanges, SimpleChanges, SimpleChange

    Demo Example: Look at

    Demo Example: Look at

    this plunker

    this plunker

  3. Alternately, you can also use an input property setter as follows:

    Alternately, you can also use an input property setter as follows:

    Alternately, you can also use an input property setter as follows:private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }

    Alternately, you can also use an input property setter as follows: private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }

  4. Documentation Link: Look here.

    Documentation Link: Look here .

  5. Demo Example: Look at this plunker.

    Demo Example: Look at this plunker .

WHICH APPROACH SHOULD YOU USE?

WHICH APPROACH SHOULD YOU USE?

If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.

If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.

However, if you want to do something when only a particular single input changes (and you don’t care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).

However, if you want to do something when only a particular single input changes (and you don't care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).

EDIT 2017–07–25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES

EDIT 2017–07–25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES

Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, provided that the data is a JS primitive datatype(string, number, boolean). However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.

Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, provided that the data is a JS primitive datatype(string, number, boolean) . However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.

  1. If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look here.

    If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look here .

  2. If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to this.

    If you are mutating data outside of the angular context (ie, externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to this .

SourceTop

Source Top

How to pass URL arguments (query string) to a HTTP request on Angular (How to pass URL arguments (query string) to a HTTP request on Angular)

154+ points ? 157,619+ viewed

154+ points ? 1 57,619+ viewed

154+ points ? 157,619+ viewed Miguel Lattuada asked,

154+ points ? 1 57,619+ viewed Miguel Lattuada asked,

Hi guys I’m creating a HTTP request on Angular, but I do not know how to add URL arguments (query string) to it.

Hi guys I'm creating a HTTP request on Angular, but I do not know how to add URL arguments (query string) to it.

this.http.get(StaticSettings.BASE_URL).subscribe((response) => this.onGetForecastResult(response.json()),(error) => this.onGetForecastError(error.json()),() => this.onGetForecastComplete()
);

Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2

Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2

Where var1, and var2 fit on my Http request object? I want to add them like an object.

Where var1, and var2 fit on my Http request object? I want to add them like an object.

{query: {var1: val1,var2: val2}
}

and then just the Http module do the job to parse it into URL query string.

and then just the Http module do the job to parse it into URL query string.

toskv answered, (216+ points)

toskv answered, (216+ points)

The HttpClient methods allow you to set the params in it’s options.

The HttpClient methods allow you to set the params in it's options.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

import {HttpClientModule} from '@angular/common/http';@NgModule({imports: [ BrowserModule, HttpClientModule ],declarations: [ App ],bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'
import {HttpClient} from '@angular/common/http'@Component({selector: 'my-app',template: `<div><h2>Hello {{name}}</h2></div>`,
})
export class App {name:string;constructor(private httpClient: HttpClient) {this.httpClient.get('/url', {params: {appid: 'id1234',cnt: '5'},observe: 'response'}).toPromise().then(response => {console.log(response);}).catch(console.log);}
}

You can find a working example here.

You can find a working example here .

For angular versions prior to version 4 you can do the same using the Http service.

For angular versions prior to version 4 you can do the same using the Http service.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

一個例子:

// Parameters obj-let params: URLSearchParams = new URLSearchParams();params.set('appid', StaticSettings.API_KEY);params.set('cnt', days.toString());//Http request-return this.http.get(StaticSettings.BASE_URL, {search: params}).subscribe((response) => this.onGetForecastResult(response.json()), (error) => this.onGetForecastError(error.json()), () => this.onGetForecastComplete());

The documentation for the Http class has more details. It can be found here and an working example here.

The documentation for the Http class has more details. It can be found here and an working example here .

SourceTop

Source Top

How do you deploy Angular apps? (How do you deploy Angular apps?)

153+ points ? 89,991+ viewed

153+ points ? 8 9,991+ viewed

153+ points ? 89,991+ viewed Joseph Assem Sobhy asked,

153+ points ? 8 9,991+ viewed Joseph Assem Sobhy asked,

How do you deploy Angular apps once they reach the production phase?

How do you deploy Angular apps once they reach the production phase?

All the guides I’ve seen so far (even on angular.io) are counting on a lite-server for serving and browserSync to reflect changes — but when you finish with development, how can you publish the app?

All the guides I've seen so far (even on angular.io ) are counting on a lite-server for serving and browserSync to reflect changes — but when you finish with development, how can you publish the app?

Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?

Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?

Amid answered, (74+ points)

Amid answered, (74+ points)

You are actually here touching two questions in one. First one is how to host your application. And as @toskv mentioned its really too broad question to be answered and depends on numerous different things. Second one is more specific — how do you prepare the deployment version of the application. You have several options here:

You are actually here touching two questions in one. First one is how to host your application. And as @toskv mentioned its really too broad question to be answered and depends on numerous different things. Second one is more specific — how do you prepare the deployment version of the application. You have several options here:

  1. Deploy as it is. Just that — no minification, concatenation, name mangling etc. Transpile all your ts project, copy all your resulting js/css/… sources + dependencies to the hosting server and your are good to go.

    Deploy as it is. Just that — no minification, concatenation, name mangling etc. Transpile all your ts project, copy all your resulting js/css/… sources + dependencies to the hosting server and your are good to go.
  2. Deploy using special bundling tools. Like webpack or systemjs builder. They come with all possibilities that are lacking in #1. You can pack all your app code into just couple of js/css/… files that you reference in your html. Systemjs buider even allows you to get rid of need to include systemjs as part of your deployment package.

    Deploy using special bundling tools. Like webpack or systemjs builder. They come with all possibilities that are lacking in #1. You can pack all your app code into just couple of js/css/… files that you reference in your html. Systemjs buider even allows you to get rid of need to include systemjs as part of your deployment package.

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your html page. You do not have to reference all your compiled js files from the page though — systemjs as a module loader will take care of that.

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your html page. You do not have to reference all your compiled js files from the page though — systemjs as a module loader will take care of that.

I know it sounds muddy — to help get you started with the #2 here are two really good sample applications:

I know it sounds muddy — to help get you started with the #2 here are two really good sample applications:

SystemJS builder: angular2 seed

SystemJS builder: angular2 seed

WebPack: angular2 webpack starter

WebPack: angular2 webpack starter

Look how they do it — and hopefully this will help you to find your way of bundling apps you make.

Look how they do it — and hopefully this will help you to find your way of bundling apps you make.

SourceTop

Source Top

ngFor with index as value in attribute (ngFor with index as value in attribute)

149+ points ? 195,294+ viewed

149+ points ? 1 95,294+ viewed

149+ points ? 195,294+ viewed Vivendi asked,

149+ points ? 1 95,294+ viewed Vivendi asked,

I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I have a simple ngFor loop which also keeps track of the current index . I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

I basically have this:

<ul *ngFor="#item of items; #i = index" data-index="#i"><li>{{item}}</li>
</ul>

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I want to store the value of #i in the attribute data-index . I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?

How can I store the index value in the data-index attribute?

Thierry Templier answered, (284+ points)

Thierry Templier answered, (284+ points)

I would use this syntax to set the index value into an attribute of the HTML element:

I would use this syntax to set the index value into an attribute of the HTML element:

<ul><li *ngFor="#item of items; #i = index" [attr.data-index]="i">{{item}}</li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview .

Update for recent angular 2 releases You have to use let to declare the value rather than #.

Update for recent angular 2 releases You have to use let to declare the value rather than # .

<ul><li *ngFor="let item of items; let i = index" [attr.data-index]="i">{{item}}</li>
</ul>

SourceTop

Source Top

Define global constants in Angular 2 (Define global constants in Angular 2)

149+ points ? 128,101+ viewed

149+ points ? 1 28,101+ viewed

149+ points ? 128,101+ viewed AndreFeijo asked,

149+ points ? 1 28,101+ viewed AndreFeijo asked,

In Angular 1.x you can define constants like this:

In Angular 1.x you can define constants like this:

angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')

What would be the equivalent in Angular2 (with Typescript)? I just don’t want to repeat the API base url over and over again in all my services.

What would be the equivalent in Angular2 (with Typescript)? I just don't want to repeat the API base url over and over again in all my services.

AndreFeijo answered, (159+ points)

AndreFeijo answered, (159+ points)

Below changes works for me on Angular 2 final version:

Below changes works for me on Angular 2 final version:

export class AppSettings {public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';@Injectable()
export class MessageService {constructor(private http: Http) { }getMessages(): Observable<Message[]> {return this.http.get(AppSettings.API_ENDPOINT+'/messages').map(response => response.json()).map((messages: Object[]) => {return messages.map(message => this.parseData(message));});}private parseData(data): Message {return new Message(data);}
}

SourceTop

Source Top

Angular — Use pipes in services and components (Angular — Use pipes in services and components)

148+ points ? 75,716+ viewed

148+ points ? 7 5,716+ viewed

148+ points ? 75,716+ viewed POSIX-compliant asked,

148+ points ? 7 5,716+ viewed POSIX-compliant asked,

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

$filter('date')(myDate, 'yyyy-MM-dd');

Is it possible to use pipes in services/components like this in Angular?

Is it possible to use pipes in services/components like this in Angular?

cexbrayat answered, (271+ points)

cexbrayat answered, (271+ points)

As usual in Angular, you can rely on dependency injection:

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';
class MyService {constructor(private datePipe: DatePipe) {}transformDate(date) {this.datePipe.transform(myDate, 'yyyy-MM-dd');}
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe :

providers: [DatePipe,...]

Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table ).

If you’re using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

SourceTop

Source Top

144+ points ? 83,326+ viewed

144+ points ? 8 3,326+ viewed

144+ points ? 83,326+ viewed Lester Burnham asked,

144+ points ? 8 3,326+ viewed Lester Burnham asked,

Obviously the beta for Angular2 is newer than new, so there’s not much information out there, but I am trying to do what I think is some fairly basic routing.

Obviously the beta for Angular2 is newer than new, so there's not much information out there, but I am trying to do what I think is some fairly basic routing.

Hacking about with the quick-start code and other snippets from the https://angular.io website has resulted in the following file structure:

Hacking about with the quick-start code and other snippets from the https://angular.io website has resulted in the following file structure:

angular-testapp/app/app.component.tsboot.tsrouting-test.component.tsindex.html

With the files being populated as follows:

With the files being populated as follows:

index.html

index.html

<html><head><base href="/"><title>Angular 2 QuickStart</title><link href="../css/bootstrap.css" rel="stylesheet"><!-- 1. Load libraries --><script src="node_modules/angular2/bundles/angular2-polyfills.js"></script><script src="node_modules/systemjs/dist/system.src.js"></script><script src="node_modules/rxjs/bundles/Rx.js"></script><script src="node_modules/angular2/bundles/angular2.dev.js"></script><script src="node_modules/angular2/bundles/router.dev.js"></script><!-- 2. Configure SystemJS --><script>System.config({packages: {        app: {format: 'register',defaultExtension: 'js'}}});System.import('app/boot').then(null, console.error.bind(console));</script></head><!-- 3. Display the application --><body><my-app>Loading...</my-app></body></html>

boot.ts

boot.ts

import {bootstrap}    from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from 'angular2/router';import {AppComponent} from './app.component'bootstrap(AppComponent, [ROUTER_PROVIDERS
]);

app.component.ts

app.component.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';import {RoutingTestComponent} from './routing-test.component';@Component({selector: 'my-app',template: `<h1>Component Router</h1><a [routerLink]="['RoutingTest']">Routing Test</a><router-outlet></router-outlet>`
})@RouteConfig([{path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])export class AppComponent { }

routing-test.component.ts

routing-test.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';@Component({template: `<h2>Routing Test</h2><p>Interesting stuff goes here!</p>`
})
export class RoutingTestComponent { }

Attempting to run this code produces the error:

Attempting to run this code produces the error:

EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("<h1>Component Router</h1><a [ERROR ->][routerLink]="['RoutingTest']">Routing Test</a><router-outlet></router-outlet>"): AppComponent@2:11

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0. However, the “working example” in one of the answers is based on pre-beta code — which may well still work, but I would like to know why the code I have created is not working.

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0 . However, the “working example” in one of the answers is based on pre-beta code — which may well still work, but I would like to know why the code I have created is not working.

Any pointers would be gratefully received!

Any pointers would be gratefully received!

Günter Z?chbauer answered, (220+ points)

Günter Z?chbauer answered, (220+ points)

>=RC.5

>=R C.5

import the RouterModule See also https://angular.io/docs/ts/latest/guide/router.html

import the RouterModule See also https://angular.io/docs/ts/latest/guide/router.html

@NgModule({ imports: [RouterModule],...
})

>=RC.2

>=R C.2

app.routes.ts

app.routes.ts

import { provideRouter, RouterConfig } from '@angular/router';export const routes: RouterConfig = [...
];export const APP_ROUTER_PROVIDERS = [provideRouter(routes)];

main.ts

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from './app.routes';bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

<=RC.1

<=RC.1

Your code is missing

Your code is missing

@Component({...directives: [ROUTER_DIRECTIVES],...)}

You can’t use directives like routerLink or router-outlet without making them known to your component.

You can't use directives like routerLink or router-outlet without making them known to your component.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outlet> to be compatible with the web-components spec which require a - in the name of custom elements.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outl et> to be compatible with the web-components spec which requ i re a - in the name of custom elements.

register globally

register globally

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...):

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...) :

provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true})

then it’s no longer necessary to add ROUTER_DIRECTIVES to each component.

then it's no longer necessary to add ROUTER_DIRECTIVES to each component.

SourceTop

Source Top

Angular 2 dynamic tabs with user-click chosen components (Angular 2 dynamic tabs with user-click chosen components)

143+ points ? 80,735+ viewed

143+ points ? 8 0,735+ viewed

143+ points ? 80,735+ viewed Cuel asked,

143+ points ? 8 0,735+ viewed Cuel asked,

I’m trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there’s plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.

I'm trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there's plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.

The instantiated component will then register itself as a new tab.

The instantiated component will then register itself as a new tab.

I’m not sure if this is the ‘best’ approach? Sofar the only guides I’ve seen are for static tabs, which doesn’t help.

I'm not sure if this is the 'best' approach? Sofar the only guides I've seen are for static tabs, which doesn't help.

So far I’ve only got the tabs service which is bootstrapped in main to persist throughout the app, looks ~something like this.

So far I've only got the tabs service which is bootstrapped in main to persist throughout the app, looks ~something like this.

export interface ITab { title: string; }@Injectable()
export class TabsService {private tabs = new Set<ITab>();addTab(title: string): ITab {let tab: ITab = { title };this.tabs.add(tab);return tab;}removeTab(tab: ITab) {this.tabs.delete(tab);}
}

Questions:

問題:

1) How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the DynamicComponentBuilder would be used?

1) How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the DynamicComponentBuilder would be used?

2) How can the components created from the inbox (on click) register themselves as tabs and also be shown? I’m guessing ng-content but I can’t find much info on how to use it

2) How can the components created from the inbox (on click) register themselves as tabs and also be shown? I'm guessing ng-content but I can't find much info on how to use it

Edit: Try to clarify

Edit: Try to clarify

Think of the inbox as a mail inbox, items are fetched as JSON and displays several items. Once one of the items is clicked, a new tab is created with that items action ‘type’. The type is then a component

Think of the inbox as a mail inbox, items are fetched as JSON and displays several items. Once one of the items is clicked, a new tab is created with that items action 'type'. The type is then a component

Edit2: Image

Edit2: Image

http://i.imgur.com/yzfMOXJ.png

http://i.imgur.com/yzfMOXJ.png

Günter Z?chbauer answered, (190+ points)

Günter Z?chbauer answered, (190+ points)

update

update

Angular 5 StackBlitz example

Angular 5 StackBlitz example

update

update

ngComponentOutlet was added to 4.0.0-beta.3

ngComponentOutlet was added to 4.0.0-beta.3

update

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

RC.7

Plunker example RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;@Input() type: Type<Component>;cmpRef: ComponentRef<Component>;private isViewInitialized:boolean = false;constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}updateComponent() {if(!this.isViewInitialized) {return;}if(this.cmpRef) {// when the `type` input changes we destroy a previously // created component before creating the new onethis.cmpRef.destroy();}let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);this.cmpRef = this.target.createComponent(factory)// to access the created instance use// this.compRef.instance.someProperty = 'someValue';// this.compRef.instance.someOutput.subscribe(val => doSomething());}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Usage example

Usage example

// Use dcl-wrapper component
@Component({selector: 'my-tabs',template: `<h2>Tabs</h2><div *ngFor="let tab of tabs"><dcl-wrapper [type]="tab"></dcl-wrapper></div>
`
})
export class Tabs {@Input() tabs;
}@Component({selector: 'my-app',template: `<h2>Hello {{name}}</h2><my-tabs [tabs]="types"></my-tabs>
`
})
export class App {// The list of components to create tabs fromtypes = [C3, C1, C2, C3, C3, C1, C1];
}@NgModule({imports: [ BrowserModule ],declarations: [ App, DclWrapper, Tabs, C1, C2, C3],entryComponents: [C1, C2, C3],bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

This changed again in Angular2 RC.5

I will update the example below but it’s the last day before vacation.

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

This Plunker example demonstrates how to dynamically create components in RC.5

Update — use ViewContainerRef.createComponent()

Update — use ViewContainerRef .createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target;@Input() type;cmpRef:ComponentRef;private isViewInitialized:boolean = false;constructor(private resolver: ComponentResolver) {}updateComponent() {if(!this.isViewInitialized) {return;}if(this.cmpRef) {this.cmpRef.destroy();}this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {this.cmpRef = this.target.createComponent(factory)// to access the created instance use// this.compRef.instance.someProperty = 'someValue';// this.compRef.instance.someOutput.subscribe(val => doSomething());});}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Plunker example RC.4Plunker example beta.17

Plunker example RC.4 Plunker example beta.17

Update — use loadNextToLocation

Update — use loadNextToLocation

export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target;@Input() type;cmpRef:ComponentRef;private isViewInitialized:boolean = false;constructor(private dcl:DynamicComponentLoader) {}updateComponent() {// should be executed every time `type` changes but not before `ngAfterViewInit()` was called // to have `target` initializedif(!this.isViewInitialized) {return;}if(this.cmpRef) {this.cmpRef.destroy();}this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {this.cmpRef = cmpRef;});}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Plunker example beta.17

Plunker example beta.17

original

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}@Input() type;ngOnChanges() {if(this.cmpRef) {this.cmpRef.dispose();}this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {this.cmpRef = cmpRef;});}
}@Component({selector: 'c1',template: `<h2>c1</h2>`})
export class C1 {
}@Component({selector: 'c2',template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({selector: 'c3',template: `<h2>c3</h2>`})
export class C3 {
}@Component({selector: 'my-tabs',directives: [DclWrapper],template: `<h2>Tabs</h2><div *ngFor="let tab of tabs"><dcl-wrapper [type]="tab"></dcl-wrapper></div>
`
})
export class Tabs {@Input() tabs;
}@Component({selector: 'my-app',directives: [Tabs]template: `<h2>Hello {{name}}</h2><my-tabs [tabs]="types"></my-tabs>
`
})
export class App {types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

There is also a way to pass data along that can be passed to the dynamically created component like ( someData would need to be passed like type )

this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {cmpRef.instance.someProperty = someData;this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

SourceTop

Source Top

Delegation: EventEmitter or Observable in Angular (Delegation: EventEmitter or Observable in Angular)

141+ points ? 78,505+ viewed

141+ points ? 7 8,505+ viewed

141+ points ? 78,505+ viewed the_critic asked,

141+ points ? 7 8,505+ viewed the_critic asked,

I am trying to implement something like a delegation pattern in Angular. When the user clicks on a nav-item, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.

I am trying to implement something like a delegation pattern in Angular. When the user clicks on a nav-item , I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.

Here is the scenario: I have a Navigation component:

Here is the scenario: I have a Navigation component:

import {Component, Output, EventEmitter} from 'angular2/core';@Component({// other properties left out for brevityevents : ['navchange'], template:`<div class="nav-item" (click)="selectedNavItem(1)"></div>`
})export class Navigation {@Output() navchange: EventEmitter<number> = new EventEmitter();selectedNavItem(item: number) {console.log('selected nav item ' + item);this.navchange.emit(item)}}

Here is the observing component:

Here is the observing component:

export class ObservingComponent {// How do I observe the event ? // <----------Observe/Register Event ?-------->public selectedNavItem(item: number) {console.log('item index changed!');}}

The key question is, how do I make the observing component observe the event in question ?

The key question is, how do I make the observing component observe the event in question ?

Mark Rajcok answered, (306+ points)

Mark Rajcok answered, (306+ points)

Update 2016–06–27: instead of using Observables, use either

Update 2016–06–27: instead of using Observables, use either

  • a BehaviorSubject, as recommended by @Abdulrahman in a comment, or

    a BehaviorSubject, as recommended by @Abdulrahman in a comment, or
  • a ReplaySubject, as recommended by @Jason Goemaat in a comment

    a ReplaySubject, as recommended by @Jason Goemaat in a comment

A Subject is both an Observable (so we can subscribe() to it) and an Observer (so we can call next() on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).

A Subject is both an Observable (so we can subscribe() to it) and an Observer (so we can call next() on it to emit a new value). We exploit this feature. A Subject allows values to be multicast to many Observers. We don't exploit this feature (we only have one Observer).

BehaviorSubject is a variant of Subject. It has the notion of “the current value”. We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.

BehaviorSubject is a variant of Subject. It has the notion of “the current value”. We exploit this: whenever we create an ObservingComponent, it gets the current navigation item value from the BehaviorSubject automatically.

The code below and the plunker use BehaviorSubject.

The code below and the plunker use BehaviorSubject.

ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1). Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first() on the subscription. You do not have to unsubscribe if you use first().

ReplaySubject is another variant of Subject. If you want to wait until a value is actually produced, use ReplaySubject(1) . Whereas a BehaviorSubject requires an initial value (which will be provided immediately), ReplaySubject does not. ReplaySubject will always provide the most recent value, but since it does not have a required initial value, the service can do some async operation before returning it's first value. It will still fire immediately on subsequent calls with the most recent value. If you just want one value, use first() on the subscription. You do not have to unsubscribe if you use first() .

import {Injectable}      from '@angular/core'
import {BehaviorSubject} from 'rxjs/BehaviorSubject';@Injectable()
export class NavService {// Observable navItem sourceprivate _navItemSource = new BehaviorSubject<number>(0);// Observable navItem streamnavItem$ = this._navItemSource.asObservable();// service commandchangeNav(number) {this._navItemSource.next(number);}
}import {Component}    from '@angular/core';
import {NavService}   from './nav.service';
import {Subscription} from 'rxjs/Subscription';@Component({selector: 'obs-comp',template: `obs component, item: {{item}}`
})
export class ObservingComponent {item: number;subscription:Subscription;constructor(private _navService:NavService) {}ngOnInit() {this.subscription = this._navService.navItem$.subscribe(item => this.item = item)}ngOnDestroy() {// prevent memory leak when component is destroyedthis.subscription.unsubscribe();}
}@Component({selector: 'my-nav',template:`<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div><div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`
})
export class Navigation {item = 1;constructor(private _navService:NavService) {}selectedNavItem(item: number) {console.log('selected nav item ' + item);this._navService.changeNav(item);}
}

Plunker

柱塞

Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don’t recommend it, but it may be instructive)

Original answer that uses an Observable: (it requires more code and logic than using a BehaviorSubject, so I don't recommend it, but it may be instructive)

So, here’s an implementation that uses an Observable instead of an EventEmitter. Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem(), and then be notified of changes via the navChange$ Observable.

So, here's an implementation that uses an Observable instead of an EventEmitter . Unlike my EventEmitter implementation, this implementation also stores the currently selected navItem in the service, so that when an observing component is created, it can retrieve the current value via API call navItem() , and then be notified of changes via the navChange$ Observable.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Observer} from 'rxjs/Observer';export class NavService {private _navItem = 0;navChange$: Observable<number>;private _observer: Observer;constructor() {this.navChange$ = new Observable(observer =>this._observer = observer).share();// share() allows multiple subscribers}changeNav(number) {this._navItem = number;this._observer.next(number);}navItem() {return this._navItem;}
}@Component({selector: 'obs-comp',template: `obs component, item: {{item}}`
})
export class ObservingComponent {item: number;subscription: any;constructor(private _navService:NavService) {}ngOnInit() {this.item = this._navService.navItem();this.subscription = this._navService.navChange$.subscribe(item => this.selectedNavItem(item));}selectedNavItem(item: number) {this.item = item;}ngOnDestroy() {this.subscription.unsubscribe();}
}@Component({selector: 'my-nav',template:`<div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div><div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>`,
})
export class Navigation {item:number;constructor(private _navService:NavService) {}selectedNavItem(item: number) {console.log('selected nav item ' + item);this._navService.changeNav(item);}
}

Plunker

柱塞

See also the Component Interaction Cookbook example, which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

See also the Component Interaction Cookbook example , which uses a Subject in addition to observables. Although the example is "parent and children communication," the same technique is applicable for unrelated components.

SourceTop

Source Top

How to add bootstrap to an angular-cli project (How to add bootstrap to an angular-cli project)

140+ points ? 166,741+ viewed

140+ points ? 1 66,741+ viewed

140+ points ? 166,741+ viewed Jerome asked,

140+ points ? 1 66,741+ viewed Jerome asked,

We want to use bootstrap 4 (4.0.0-alpha.2) in our app generated with angular-cli 1.0.0-beta.5 (w/ node v6.1.0).

We want to use bootstrap 4 (4.0.0-alpha.2) in our app generated with angular-cli 1.0.0-beta.5 (w/ node v6.1.0).

After getting bootstrap and its dependencies with npm, our first approach consisted in adding them in angular-cli-build.js:

After getting bootstrap and its dependencies with npm, our first approach consisted in adding them in angular-cli-build.js :

'bootstrap/dist/**/*.min.+(js|css)',  'jquery/dist/jquery.min.+(js|map)',  'tether/dist/**/*.min.+(js|css)',

and import them in our index.html

and import them in our index.html

<script src="vendor/jquery/dist/jquery.min.js"></script><script src="vendor/tether/dist/js/tether.min.js"></script><link rel="stylesheet" type="text/css" href="vendor/bootstrap/dist/css/bootstrap.min.css"><script src="vendor/bootstrap/dist/js/bootstrap.min.js"></script>

This worked fine with ng serve but as soon as we produced a build with -prod flag all these dependencies disappeared from dist/vendor (surprise !).

This worked fine with ng serve but as soon as we produced a build with -prod flag all these dependencies disappeared from dist/vendor (surprise !).

How we are intended to handle such scenario (i.e. loading bootstrap scripts) in a project generated with angular-cli ?

How we are intended to handle such scenario (ie loading bootstrap scripts) in a project generated with angular-cli ?

We had the following thoughts but we don’t really know which way to go…

We had the following thoughts but we don't really know which way to go…

  • use a CDN ? but we would rather serve these files to guarantee that they will be available

    use a CDN ? but we would rather serve these files to guarantee that they will be available
  • copy dependencies to dist/vendor after our ng build -prod ? But that seems like something angular-cli should provide since it 'takes care' of the build part ?

    copy dependencies to dist/vendor after our ng build -prod ? But that seems like something angular-cli should provide since it 'takes care' of the build part ?

  • adding jquery, bootstrap and tether in src/system-config.ts and somehow pull them into our bundle in main.ts ? But that seemed wrong considering that we are not going to explicitly use them in our application’s code (unlike moment.js or something like lodash, for example)

    adding jquery, bootstrap and tether in src/system-config.ts and somehow pull them into our bundle in main.ts ? But that seemed wrong considering that we are not going to explicitly use them in our application's code (unlike moment.js or something like lodash, for example)

pd farhad answered, (202+ points)

pd farhad answered, (202+ points)

**IMPORTANT UPDATE: ng2-bootstrap is now replaced by ngx-bootstrap **

**IMPORTANT UPDATE: ng2-bootstrap is now replaced by ngx-bootstrap **

ngx-bootstrap supports both angular 3 and 4.

ngx-bootstrap supports both angular 3 and 4.

Update : 1.0.0-beta.11-webpack or above versions

Update : 1.0.0-beta.11-webpack or above versions

First of all check your angular-cli version with the following command in the terminal: ng -v

First of all check your angular-cli version with the following command in the terminal: ng -v

If your angular-cli version is greater than 1.0.0-beta.11-webpack then you should follow these steps:

If your angular-cli version is greater than 1.0.0-beta.11-webpack then you should follow these steps:

  1. install ngx-bootstrap and bootstrap:

    install ngx-bootstrap and bootstrap:

    install ngx-bootstrap and bootstrap:npm install ngx-bootstrap bootstrap --save

    install ngx-bootstrap and bootstrap: npm install ngx-bootstrap bootstrap --save

This line installs bootstrap 3 nowadays, but can install bootstrap 4 in future. Keep in mind ngx-bootstrap supports both versions.

This line installs bootstrap 3 nowadays, but can install bootstrap 4 in future. Keep in mind ngx-bootstrap supports both versions.

  1. open src/app/app.module.ts and add

    open src/app/app.module.ts and add

    open src/app/app.module.ts and addimport { AlertModule } from 'ngx-bootstrap'; ... @NgModule({ ... imports: [AlertModule.forRoot(), ... ], ... })

    open src/app/app.module.ts and add import { AlertModule } from 'ngx-bootstrap'; ... @NgModule({ ... imports: [AlertModule.forRoot(), ... ], ... })

  2. open angular-cli.json and insert a new entry into the styles array

    open angular-cli.json and insert a new entry into the styles array

    open angular-cli.json and insert a new entry into the styles array"styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ],

    open angular-cli.json and insert a new entry into the styles array "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ],

  3. open src/app/app.component.html and add

    open src/app/app.component.html and add

    open src/app/app.component.html and add<alert type="success">hello&lt;/alert>

    open src/app/app.component.html and add <alert type="success">hello&l t;/alert>

1.0.0-beta.10 or below versions:

1.0.0-beta.10 or below versions:

And, if your angular-cli version is 1.0.0-beta.10 or below versions then you can use below steps.

And, if your angular-cli version is 1.0.0-beta.10 or below versions then you can use below steps.

First go to the project directory and type

First go to the project directory and type

npm install ngx-bootstrap --save

then open your angular-cli-build.js and add this line

then open your angular-cli-build.js and add this line

vendorNpmFiles: [..................'ngx-bootstrap/**/*.js',....................]

now open your src/system-config.ts, write

now open your src/system-config.ts , write

const map:any = {..................'ngx-bootstrap': 'vendor/ngx-bootstrap',....................
}

and

const packages: any = {'ngx-bootstrap': {format: 'cjs',defaultExtension: 'js',main: 'ngx-bootstrap.js'}
};

SourceTop

Source Top

access key and value of object using *ngFor (access key and value of object using *ngFor)

136+ points ? 139,816+ viewed

136+ points ? 1 39,816+ viewed

136+ points ? 139,816+ viewed Pardeep Jain asked,

136+ points ? 1 39,816+ viewed Pardeep Jain asked,

Bit confused about how to get Key and Value of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like

Bit confused about how to get Key and Value of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like

ng-repeat="(key, value) in demo"

but in angular2 i don’t know i tired the same but did’t get successful. i have tried the below code but did’t run please tell me where i am doing wrong.

but in angular2 i don't know i tired the same but did't get successful. i have tried the below code but did't run please tell me where i am doing wrong.

<ul><li *ngFor='#key of demo'>{{key}}</li>
</ul>demo = {'key1': [{'key11':'value11'}, {'key12':'value12'}],'key2': [{'key21':'value21'}, {'key22':'value22'}],}

here is plnkr where i have tried the same : http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

here is plnkr where i have tried the same : http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

I want to get key1 and key2 dynamically using *ngFor. How to get it? i searched a lot found idea of using pipe but how to use i dont know. is there any inbuild pipe for doing same in angular2 ?

I want to get key1 and key2 dynamically using *ngFor. How to get it? i searched a lot found idea of using pipe but how to use i dont know. is there any inbuild pipe for doing same in angular2 ?

Thierry Templier answered, (134+ points)

Thierry Templier answered, (134+ points)

You could create a custom pipe to return the list of key for each element. Something like that:

You could create a custom pipe to return the list of key for each element. Something like that:

import { PipeTransform, Pipe } from '@angular/core';@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {transform(value, args:string[]) : any {let keys = [];for (let key in value) {keys.push(key);}return keys;}
}

and use it like that:

and use it like that:

<tr *ngFor="let c of content">           <td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>

Edit

Edit

You could also return an entry containing both key and value:

You could also return an entry containing both key and value:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {transform(value, args:string[]) : any {let keys = [];for (let key in value) {keys.push({key: key, value: value[key]});}return keys;}
}

and use it like that:

and use it like that:

<span *ngFor="let entry of content | keys">           Key: {{entry.key}}, value: {{entry.value}}
</span>

SourceTop

Source Top

Angular exception: Can't bind to 'ngFor' since it isn't a known native property (Angular exception: Can’t bind to ‘ngFor’ since it isn’t a known native property)

134+ points ? 63,054+ viewed

134+ points ? 6 3,054+ viewed

134+ points ? 63,054+ viewed Mark Rajcok asked,

134+ points ? 6 3,054+ viewed Mark Rajcok asked,

What am I doing wrong?

我究竟做錯了什么?

import {bootstrap, Component} from 'angular2/angular2'@Component({selector: 'conf-talks',template: `<div *ngFor="talk of talks">{{talk.title}} by {{talk.speaker}}<p>{{talk.description}}</div>`
})
class ConfTalks {talks = [ {title: 't1', speaker: 'Brian', description: 'talk 1'},{title: 't2', speaker: 'Julie', description: 'talk 2'}];
}
@Component({selector: 'my-app',directives: [ConfTalks],template: '<conf-talks></conf-talks>'
})
class App {}
bootstrap(App, [])

The error is

The error is

EXCEPTION: Template parse errors:
Can't bind to 'ngFor' since it isn't a known native property
("<div [ERROR ->]*ngFor="talk of talks">

Mark Rajcok answered, (325+ points)

Mark Rajcok answered, (325+ points)

I missed let in front of talk:

I missed let in front of talk :

<div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead. <div *ngFor="#talk of talks"> now becomes <div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead. <div *ngFor="#talk of talk s"> now be comes <div *ngFor="let talk o f talks">

Original answer:

Original answer:

I missed # in front of talk:

I missed # in front of talk :

<div *ngFor="#talk of talks">

It is so easy to forget that #. I wish the Angular exception error message would instead say:you forgot that # again.

It is so easy to forget that # . I wish the Angular exception error message would instead say: you forgot that # again .

SourceTop

Source Top

How to add font-awesome to Angular 2 + CLI project (How to add font-awesome to Angular 2 + CLI project)

132+ points ? 71,934+ viewed

132+ points ? 7 1,934+ viewed

132+ points ? 71,934+ viewed Nik asked,

132+ points ? 7 1,934+ viewed Nik asked,

I’m using Angular 2+ and Angular CLI.

I'm using Angular 2+ and Angular CLI.

How do I add font-awesome to my project?

How do I add font-awesome to my project?

AIon answered, (285+ points)

AIon answered, (285+ points)

After Angular 2.0 final release, the structure of the Angular2 CLI project has been changed — you don’t need any vendor files, no system.js — only webpack. So you do:

After Angular 2.0 final release, the structure of the Angular2 CLI project has been changed — you don't need any vendor files, no system.js — only webpack. So you do:

  1. npm install font-awesome --save

    npm install font-awesome --save

  2. In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below:

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below:

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below: “apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ] ]

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below: “apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ] ]

  3. Place some font-awesome icons in any html file you want:

    Place some font-awesome icons in any html file you want:

    Place some font-awesome icons in any html file you want: <i class=”fa fa-american-sign-language-interpreting fa-5x” aria-hidden=”true”> </i>

    Place some font-awesome icons in any html file you want: <i class=”fa fa-american-sign-language-interpreting fa-5x” aria-hidden=”true”> </i>

  4. Run ng build and ng serve again - because the watchers are only for the src folder and angular-cli.json is not observed for changes.

    Run ng build and ng serve again - because the watchers are only for the src folder and angular-cli.json is not observed for changes.

  5. Enjoy your awesome icons!

    Enjoy your awesome icons!

SourceTop

Source Top

Difference between HTTP and HTTPClient in angular 4? (Difference between HTTP and HTTPClient in angular 4?)

130+ points ? 47,082+ viewed

130+ points ? 4 7,082+ viewed

130+ points ? 47,082+ viewed Aioub Amini asked,

130+ points ? 4 7,082+ viewed Aioub Amini asked,

I want to know which one to use to build a mock web service to test the Angular program?

I want to know which one to use to build a mock web service to test the Angular program?

AngularInDepth.com answered, (208+ points)

AngularInDepth.com answered, (208+ points)

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';@NgModule({imports: [BrowserModule,HttpClientModule],...class MyService() {constructor(http: HttpClient) {...}

It’s an upgraded version of http from @angular/http module with the following improvements:

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipeline

    Interceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objects

    Immutable request/response objects
  • Progress events for both request upload and response download

    Progress events for both request upload and response download

You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.

You can read about how it works in Insider's guide into interceptors and HttpClient mechanics in Angular .

  • Typed, synchronous response body access, including support for JSON body types

    Typed, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsed

    JSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing framework

    Post-request verification & flush based testing framework

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.

Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs .

Also pay attention that old http was injected using Http class token instead of the new HttpClient:

Also pay attention that old http was injected using Http class token instead of the new HttpClient :

import { HttpModule } from '@angular/http';@NgModule({imports: [BrowserModule,HttpModule],...class MyService() {constructor(http: Http) {...}

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS:

Also, new HttpClient seem to require tslib in runtime, so you have to install it npm i tslib and update system.config.js if you're using SystemJS :

map: {...'tslib': 'npm:tslib/tslib.js',

And you need to add another mapping if you use SystemJS:

And you need to add another mapping if you use SystemJS:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

SourceTop

Source Top

That’s all for today. if you found this article helpful please help me to share it. ? ? ?

今天就這些。 if you found this article helpful please help me to share it. ? ? ?

Follow me on Medium or Twitter to read more about angular, webpack, typescript, nodejs and javascript! ? ? ?

Follow me on Medium or Twitter to read more about angular, webpack, typescript, nodejs and javascript!

翻譯自: https://www.freecodecamp.org/news/48-answers-on-stack-overflow-to-the-most-popular-angular-questions-52f9eb430ab0/

angular面試題及答案

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394683.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394683.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394683.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c++分治法求最大最小值實現_最優化計算與matlab實現(12)——非線性最小二乘優化問題——G-N法...

參考資料《精通MATLAB最優化計算&#xff08;第二版&#xff09;》編程工具Matlab 2019a目錄石中居士&#xff1a;最優化計算與Matlab實現——目錄?zhuanlan.zhihu.com非線性最小二乘優化問題非線性最小二乘優化也叫無約束極小平方和函數問題&#xff0c;它是如下無約束極小問…

win7 IIS7環境下部署PHP 7.0

最近在本機電腦win7 II7環境下部署PHP 7.0遇到一些問題&#xff0c;將之記錄下來 簡要步驟如下&#xff1a; 1、到php官網下載php&#xff0c;由于是IIS環境要下載非線程安全的版本&#xff0c;我下載的是7.0.13 2、解壓到本地文件目錄下 3、通過控制臺進入到php文件目錄&#…

《Oracle高性能自動化運維》一一3.3 Redo產生場景

3.3 Redo產生場景我們知道&#xff0c;Oracle Redo是以條目&#xff08;Redo Entries/Records&#xff09;的形式記錄數據庫的所有更改操作&#xff08;OP&#xff09;。更改操作主要包括&#xff1a;數據庫物理文件更改&#xff1a;主要指的是數據庫物理文件的增減等操作&…

智能算法(GA、DBO等)求解零空閑流水車間調度問題(NIFSP)

先做一個聲明&#xff1a;文章是由我的個人公眾號中的推送直接復制粘貼而來&#xff0c;因此對智能優化算法感興趣的朋友&#xff0c;可關注我的個人公眾號&#xff1a;啟發式算法討論。我會不定期在公眾號里分享不同的智能優化算法&#xff0c;經典的&#xff0c;或者是近幾年…

《構建之法》讀后感 二

個人感受部分&#xff1a; 01. 過去的我對自己的職業沒有一個規劃&#xff0c;認為讀大學就是拿畢業證&#xff0c;至于以后找到什么樣的工作從來沒有考慮過。在拿到一個軟件作業時&#xff0c;總是在設計階段就把它想得特別完美&#xff0c;想讓他沒有任何出錯的做出來&#x…

android 簡單實現圓角,Android 實現圓角圖片的簡單實例

Android 實現圓角圖片的簡單實例實現效果圖&#xff1a;本來想在網上找個圓角的例子看一看&#xff0c;不盡人意啊&#xff0c;基本都是官方的Demo的那張原理圖&#xff0c;稍后會貼出。于是自己自定義了個View&#xff0c;實現圖片的圓角以及圓形效果。效果圖&#xff1a;Andr…

zookeeper介紹及集群的搭建(利用虛擬機)

ZooKeeper ?   ZooKeeper是一個分布式的&#xff0c;開放源碼&#xff08;apache&#xff09;的分布式應用程序協調服務&#xff0c;是Google的Chubby一個開源的實現&#xff0c;是Hadoop和Hbase、dubbox、kafka的重要組件。它主要用來解決分布式集群中應用系統的一致性問題…

pythondict初始化_利用defaultdict對字典進行全局初始化。

通常我們在操作字典時&#xff0c;如果讀取的鍵未被初始化&#xff0c;則會拋出KeyError的錯誤&#xff0c;這個是我們都很熟悉的。那么一般的解決方式是使用異常處理或者是調用字典的get方法來避免出現這個異常。 可以看到&#xff0c;這兩種寫法都比較繁瑣&#xff0c;第二種…

標準庫類型String

定義和初始化string對象 初始化string對象方式 string s1 默認初始化&#xff0c;s1是一個空串 string s2(s1) s2是s1的副本 string s2 s1 等價于s2(s1), s2是s1的副本 string s3("value") s3是字面值"value"的副本&#xff0c;除了字面值最后的那個…

輕量級數據庫中間件利器Sharding-JDBC深度解析(有彩蛋)

講師介紹張亮 當當架構部總監 負責分布式中間件和私有云平臺建設 目前主導開源項目&#xff1a;Elastic-Job及Sharding-JDBC 主題簡介&#xff1a; 1、關系型數據庫中間件核心功能介紹 2、Sharding-JDBC架構及內核解析 3、Sharding-JDBC未來展望 一、關系型數據庫中間件核心功…

python字典嵌套字典的情況下獲取某個key的value

最近在用python寫接口的測試程序&#xff0c;期間用到解析字典獲取某個key的value&#xff0c;由于多個接口返回的字典格式不是固定的并存在多層嵌套的情況。在字典的方法中也沒有找到可直接達到目的的方法(也可能是我對字典的方法了解的不深的緣故)&#xff0c;于是自己寫了個…

系統在此應用程序堆棧溢出_從部署我的第一個完整堆棧Web應用程序中學到的經驗教訓...

系統在此應用程序堆棧溢出by Will Abramson威爾艾布拉姆森(Will Abramson) 從部署我的第一個完整堆棧Web應用程序中學到的經驗教訓 (Lessons learned from deploying my first full-stack web application) I recently achieved one of my long-term goals: deploying my firs…

const 常量_條款03:盡可能使用const

const 允許你指定一個語義約束&#xff08;也就是指定一個“不該被改動”的對象&#xff09;&#xff0c;而編譯器會強制實施這項約束。1、const指針如果關鍵字const出現在星號左邊&#xff0c;表示被指物是常量&#xff1b;如果出現在星號右邊&#xff0c;表示指針自身是常量&…

javascript高級程序設計---js事件思維導圖

繪制思維軟件與平時用的筆記&#xff0c;以及導出功能&#xff0c;這三個問題綜合起來&#xff0c;于是我把思維導圖分開畫 1、js事件的基本概念 2、js事件的事件處理程序 3、js事件的事件對象 轉載于:https://www.cnblogs.com/Jamie1032797633/p/10567419.html

jq挑戰30天——打字機效果+小程序

<!doctype html><html><head><meta charset"utf-8"><title>基于jQuery實現的打字機效果-jq22.com</title><script src"http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script><style></…

和 Thrift 的一場美麗邂逅

一. 與 Thrift 的初識 也許大多數人接觸 Thrift 是從序列化開始的。每次搜索 “java序列化” “方式”、“對比” 或 “性能” 等關鍵字時&#xff0c;搜索引擎總是會返回一大堆有關各種序列化方式的使用方法或者性能對比的結果給你&#xff0c;而其中必定少不了 Thrift&#…

instagram技術_Instagram9位科技女孩進行技術采訪的主要技巧

instagram技術by Rachel通過瑞秋 Instagram9位科技女孩進行技術采訪的主要技巧 (Top tips for technical interviews from nine of Instagram’s tech girls) My job-hunt came to an end a few weeks ago. After endless phone interviews, coding challenges, and on-sites,…

彈出框 每次打開 滾動條置頂_微信置頂文字怎么弄?微信置頂一句話教程

今日支付寶紅包支付寶首頁搜索511501453馬上領取紅包(支付寶雙十二活動&#xff0c;瓜分15億紅包)(領取后一定要記得使用&#xff0c;不然會浪費的呦&#xff0c;更會影響第二天的領取&#xff01;)奶思靚機“ 一 個 有 用 的 公 眾 號 の ”嗨&#xff0c;最近很流行在微信上面…

Python學習_字符串格式化

#!/usr/bin/env python # -*- coding:utf-8 -*-# 百分號格式化 # %[(name)[flags][width].[precision]]typecode # name : 指定占位符的key # flags : - 空格 0 # width : 寬度 # precision : 小數點后保留的位數 # typecode : 必需,數據類型 # 字符串里面有%的時候, %%表示一…

python 3 面向過程編程

python 3 面向過程編程 核心是過程&#xff08;流水線式思維&#xff09;&#xff0c;過程即解決問題的步驟&#xff0c;面向過程的設計就像設計好一條工業流水線&#xff0c;是一種機械式的思維方式。 1、優點&#xff1a;程序結構清晰&#xff0c;可以把復雜的問題簡單化&…