angular面试题及答案_关于最流行的Angular问题的StackOverflow上的48个答案
angular面試題及答案
by Shlomi Levi
通過Shlomi Levi
關(guān)于最流行的Angular問題的StackOverflow上的48個(gè)答案 (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收集了最常見的問題和解答。 這些問題是根據(jù)獲得的最高分?jǐn)?shù)來選擇的。 無(wú)論您是專家還是初學(xué)者,都可以從他人的經(jīng)驗(yàn)中學(xué)到東西。
目錄 (Table of Contents)
Angular — Promise vs Observable
角度—承諾與可觀察
Difference between Constructor and ngOnInit
構(gòu)造函數(shù)和ngOnInit之間的區(qū)別
Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’
無(wú)法綁定到“ ngModel”,因?yàn)樗皇恰?input”的已知屬性
Angular HTML binding
角度HTML綁定
Angular/RxJs When should I unsubscribe from `Subscription`
Angular / RxJs我應(yīng)該何時(shí)退訂`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應(yīng)用進(jìn)行生產(chǎn)
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錯(cuò)誤http.get(…).map的角度HTTP GET不是[null]中的函數(shù)
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’
無(wú)法綁定到“ formGroup”,因?yàn)樗皇恰?form”的已知屬性
Angular DI Error — EXCEPTION: Can’t resolve all parameters
角度DI錯(cuò)誤—例外:無(wú)法解析所有參數(shù)
Angular — Set headers for every request
Angular —為每個(gè)請(qǐng)求設(shè)置標(biāo)題
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中的對(duì)象
What is difference between declarations, providers and import in NgModule
NgModule中的聲明,提供程序和導(dǎo)入之間有什么區(qū)別
In Angular, how do you determine the active route?
在Angular中,如何確定活動(dòng)路線?
Angular CLI SASS options
Angular CLI SASS選項(xiàng)
Triggering change detection manually in Angular
在Angular中手動(dòng)觸發(fā)變化檢測(cè)
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
角度異常:無(wú)法綁定到“ ngForIn”,因?yàn)樗皇且阎谋緳C(jī)屬性
*ngIf and *ngFor on same element causing error
* ngIf和* ngFor在同一元素上導(dǎo)致錯(cuò)誤
What is the Angular equivalent to an AngularJS $watch?
Angular等效于AngularJS $ watch?
Importing lodash into angular2 + typescript application
將lodash導(dǎo)入angular2 +打字稿應(yīng)用程序
How to detect a route change in Angular?
如何在Angular中檢測(cè)路線變化?
Global Events in Angular
Angular中的全球事件
What are differences between SystemJS and Webpack?
SystemJS和Webpack有什么區(qū)別?
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?
如何檢測(cè)Angular中@Input()值何時(shí)更改?
How to pass url arguments (query string) to a HTTP request on Angular
如何將url參數(shù)(查詢字符串)傳遞給Angular上的HTTP請(qǐng)求
How do you deploy Angular apps?
您如何部署Angular應(yīng)用程序?
ngFor with index as value in attribute
ngFor,其中索引作為屬性中的值
Define global constants in Angular 2
在Angular 2中定義全局常量
Angular — Use pipes in services and components
角度—在服務(wù)和組件中使用管道
Angular2 Exception: Can’t bind to ‘routerLink’ since it isn’t a known native property
Angular2異常:由于它不是已知的本機(jī)屬性,因此無(wú)法綁定到“ routerLink”
Angular 2 dynamic tabs with user-click chosen components
帶有用戶單擊所選組件的Angular 2動(dòng)態(tài)選項(xiàng)卡
Delegation: EventEmitter or Observable in Angular
委托:EventEmitter或可觀察到的Angular
How to add bootstrap to an angular-cli project
如何將引導(dǎo)程序添加到angular-cli項(xiàng)目
access key and value of object using *ngFor
使用* ngFor訪問對(duì)象的鍵和值
Angular exception: Can’t bind to ‘ngFor’ since it isn’t a known native property
角度異常:無(wú)法綁定到“ ngFor”,因?yàn)樗皇且阎谋緳C(jī)屬性
How to add font-awesome to Angular 2 + CLI project
如何將真棒字體添加到Angular 2 + CLI項(xiàng)目
Difference between HTTP and HTTPClient in angular 4?
HTTP和HTTPClient在角度4中的區(qū)別?
Enjoy!
請(qǐng)享用!
角度—承諾與可觀察 (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中Promise和Observable之間的區(qū)別嗎?
An example on each would be helpful in understanding both the cases. In what scenario can we use each case?
每個(gè)示例均有助于理解這兩種情況。 在什么情況下我們可以使用每種情況?
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.
當(dāng)異步操作完成或失敗時(shí), Promise處理單個(gè)事件 。
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.
注意:那里有Promise庫(kù)支持取消,但是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.
一個(gè)Observable就像一個(gè)Stream (在許多語(yǔ)言中),并且允許傳遞零個(gè)或多個(gè)事件,其中每個(gè)事件都被調(diào)用回調(diào)。
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.
通常, Observable比Promise更為可取,因?yàn)樗峁┝薖romise等功能。 使用Observable ,您要處理0、1或多個(gè)事件都沒有關(guān)系。 在每種情況下,您都可以使用相同的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也具有可取消的優(yōu)勢(shì)。 如果不再需要對(duì)服務(wù)器的HTTP請(qǐng)求或其他昂貴的異步操作的結(jié)果,則Observable的Subscription可以取消該預(yù)訂,而Promise最終將調(diào)用成功或失敗的回調(diào),即使您不需要需要通知或它提供的結(jié)果了。
Observable provides operators like map, forEach, reduce, ... similar to an array
Observable提供類似于map , forEach , reduce ,...的運(yùn)算符 ,類似于數(shù)組
There are also powerful operators like retry(), or replay(), ... that are often quite handy.
還有一些功能強(qiáng)大的運(yùn)算符,例如retry()或replay() ……通常非常方便。
SourceTop
來源 頂部
構(gòu)造函數(shù)和ngOnInit之間的區(qū)別 (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默認(rèn)提供生命周期掛鉤ngOnInit 。
Why should ngOnInit be used, if we already have a constructor?
如果我們已經(jīng)有了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是該類的默認(rèn)方法,該方法在實(shí)例化該類時(shí)執(zhí)行,并確保該類及其子類中字段的正確初始化。 有角或更好的依賴注入器(DI)分析構(gòu)造函數(shù)參數(shù),并在通過調(diào)用new MyClass()創(chuàng)建新實(shí)例時(shí)嘗試尋找與構(gòu)造函數(shù)參數(shù)類型匹配的提供程序,將其解析并將其傳遞給構(gòu)造函數(shù),例如
new MyClass(someArg);ngOnInit is a lifecycle hook called by Angular2 to indicate that Angular is done creating the component.
ngOnInit是ngOnInit調(diào)用的生命周期掛鉤,以指示Angular已完成創(chuàng)建組件。
We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice):
我們必須導(dǎo)入OnInit才能這樣使用(實(shí)際上,強(qiáng)制實(shí)施OnInit不是強(qiáng)制性的,但被認(rèn)為是好的做法):
import {Component, OnInit} from '@angular/core';then to use the method of OnInit we have to implement in the class like this.
然后要使用OnInit的方法,我們必須在此類中實(shí)現(xiàn)。
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用于所有的初始化/聲明,并避免在構(gòu)造函數(shù)中起作用。 構(gòu)造函數(shù)應(yīng)僅用于初始化類成員,而不應(yīng)執(zhí)行實(shí)際的“工作”。
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.
因此,您應(yīng)該使用constructor()來設(shè)置依賴注入,而無(wú)需過多設(shè)置。 ngOnInit()是“開始”的更好位置-解析組件綁定的位置/位置。
For more information refer here:
有關(guān)更多信息,請(qǐng)參見此處:
https://angular.io/api/core/OnInit
https://angular.io/api/core/OnInit
Angular 2 Component Constructor Vs OnInit
Angular 2組件構(gòu)造函數(shù)與OnInit
SourceTop
來源 頂部
無(wú)法綁定到“ ngModel”,因?yàn)樗皇恰?input”的已知屬性 (Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’)
442+ points ? 246,901+ viewed
442+點(diǎn)? 已查看2 46,901+
442+ points ? 246,901+ viewed abreneliere asked,
442+點(diǎn)? 2 46,901+瀏覽過abreneliere詢問,
I’ve got the following error when launching my Angular app, even if the component is not displayed.
即使未顯示組件,啟動(dòng)我的Angular應(yīng)用程序時(shí)也會(huì)出現(xiàn)以下錯(cuò)誤。
I have to comment out the so that my app works.
我必須注釋掉,這樣我的應(yīng)用才能正常工作。
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.
我在看英雄拔毛器,但沒什么區(qū)別。
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應(yīng)用程序,并且要顯示HTML響應(yīng)。 我怎么做? 如果我僅使用綁定語(yǔ)法{{myVal}}它將對(duì)所有HTML字符進(jìn)行編碼(當(dāng)然)。
I need somehow to bind the inner html of a div to the variable value.
我需要以某種方式將div的內(nèi)部html綁定到變量值。
prolink007 answered, (691+ points)
prolink007 回答,(超過691分)
The correct syntax is now the following:
現(xiàn)在,正確的語(yǔ)法如下:
<div [innerHTML]="theHtmlString"></div>Working in 5.2.6
在5.2.6工作
Documentation Reference
文檔參考
SourceTop
來源 頂部
Angular / RxJs我應(yīng)該何時(shí)退訂`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?
我應(yīng)該何時(shí)在NgOnDestroy生命周期中存儲(chǔ)Subscription實(shí)例并調(diào)用unsubscribe() ,何時(shí)可以忽略它們?
Saving all subscriptions introduces a lot of mess into component code.
保存所有訂閱會(huì)在組件代碼中帶來很多麻煩。
HTTP Client Guide ignore subscriptions like this:
HTTP客戶端指南會(huì)忽略這樣的訂閱:
getHeroes() {this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes,error => this.errorMessage = <any>error); }In the same time Route & Navigation Guide says that:
同時(shí),《 路線與導(dǎo)航指南 》指出:
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談到了這個(gè)問題(我什至向他展示了這個(gè)答案,他說的是正確的),但是他告訴我Angular的文檔小組對(duì)這個(gè)問題的解決方案尚未發(fā)布(盡管他們正在努力使其獲得批準(zhǔn)) )。 他還告訴我,我可以通過即將提出的官方建議來更新我的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.
今后我們應(yīng)該使用的解決方案是添加一個(gè)private ngUnsubscribe: Subject = new Subject(); 所有在其類代碼中具有.subscribe()調(diào)用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所述 )是在我們的每個(gè).subscribe()調(diào)用之前調(diào)用.takeUntil(this.ngUnsubscribe) ,這將確保在銷毀組件時(shí)清除所有訂閱。
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教程的“路由”一章現(xiàn)在指出以下內(nèi)容:“路由器管理它提供的可觀察對(duì)象并本地化訂閱。 當(dāng)組件被銷毀時(shí),訂閱將被清除,以防止內(nèi)存泄漏,因此我們無(wú)需取消訂閱可觀察到的路由參數(shù)。” — 馬克·拉杰克 ( 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.
這是針對(duì)有關(guān)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服務(wù)和ActivatedRoute.params 。
— —原始答案 (— — Original Answer)
TLDR:
TLDR:
For this question there are (2) kinds of Observables - finite value and infinite value.
對(duì)于此問題,有(2)種Observables值- 有限值和無(wú)限值。
http Observables produce finite (1) values and something like a DOM event listener Observables produce infinite values.
http Observables產(chǎn)生有限 (1)值,類似DOM event listener東西Observables產(chǎn)生無(wú)限值。
If you manually call subscribe (not using async pipe), then unsubscribe from infinite Observables.
如果您手動(dòng)調(diào)用subscribe (不使用異步管道),則unsubscribe 無(wú)限的 Observables 。
Don’t worry about finite ones, RxJs will take care of them.
不必?fù)?dān)心有限的RxJs會(huì)照顧他們。
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)
他指出(為清晰起見,我進(jìn)行了重組,重點(diǎn)是我的)
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上有關(guān)Observables的視頻中提到, they clean up after themselves ……在complete的Observables的背景下(例如Promises,由于它們總是產(chǎn)生1值并結(jié)束,所以它們總是完成的-我們從不擔(dān)心從Promises退訂到確保他們清理了xhr事件監(jiān)聽器,對(duì)吧?)。
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?
什么時(shí)候our Observable has a longer lifespan than our subscription短語(yǔ)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.
它適用于在組件內(nèi)部創(chuàng)建預(yù)訂,而該組件在Observable完成之前被銷毀(或未“長(zhǎng)久”)的情況。
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!
我的意思是,如果我們訂閱一個(gè)http請(qǐng)求或一個(gè)發(fā)出10個(gè)值的Observable,并且在該http請(qǐng)求返回或發(fā)出10個(gè)值之前銷毀了我們的組件,我們還是可以的!
When the request does return or the 10th value is finally emitted the Observable will complete and all resources will be cleaned up.
當(dāng)請(qǐng)求確實(shí)返回或最終發(fā)出第十個(gè)值時(shí), 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指南中查看此示例 ,則可以看到對(duì)route.params的Subscription確實(shí)需要unsubscribe()因?yàn)槲覀儾恢肋@些params何時(shí)會(huì)停止更改(發(fā)出新值)。
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.
通過導(dǎo)航可以破壞該組件,在這種情況下,路由參數(shù)可能仍會(huì)更改(它們可能會(huì)在技術(shù)上更改,直到應(yīng)用程序結(jié)束),并且由于尚未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中進(jìn)行操作。
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?
如何從類定義中抓住對(duì)p或input元素的引用?
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注入到組件的構(gòu)造函數(shù)中來通過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中,我會(huì)寫
<div ng-show="myVar">stuff</div>How can I do this in Angular?
如何在Angular中做到這一點(diǎn)?
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有一些問題,因?yàn)樗赡芘cdisplay屬性CSS沖突。
See how some in Plunker example doesn't get hidden because it has a style
看看在Plunker示例中如何隱藏some樣式,因?yàn)樗哂袠邮?
:host {display: block;}set. (This might behave differently in other browsers — I tested with Chrome 50)
組。 (這在其他瀏覽器中可能會(huì)有所不同-我在Chrome 50上進(jìn)行了測(cè)試)
workaround
解決方法
You can fix it by adding
您可以通過添加來修復(fù)它
[hidden] { display: none !important;}To a global style in index.html.
為index.html的全局樣式。
another pitfall
另一個(gè)陷阱
hidden="false" hidden="{{false}}" hidden="{{isHidden}}" // isHidden = false;are the same as
與...相同
hidden="true"and will not show the element.
并且不會(huì)顯示該元素。
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"將分配被認(rèn)為是真實(shí)的字符串"false"只有值false或刪除屬性才能使該元素可見。
Using {{}} also converts the expression to a string and won't work as expected.
使用{{}}還會(huì)將表達(dá)式轉(zhuǎn)換為字符串,將無(wú)法正常工作。
Only binding with [] will work as expected because this false is assigned as false instead of "false".
只有與[]綁定才能按預(yù)期工作,因?yàn)榇薴alse被分配為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中刪除了它的內(nèi)容,而[hidden]修改了display屬性,僅指示瀏覽器不顯示內(nèi)容,但DOM仍然包含它。
SourceTop
來源 頂部
如何捆綁Angular應(yīng)用進(jìn)行生產(chǎn) (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.
我想在此線程中跟蹤和更新最新的最佳(也是最簡(jiǎn)單的)方法,以便將Angular(版本2、4…)捆綁在一起,以在實(shí)時(shí)Web服務(wù)器上進(jìn)行生產(chǎn)。
Please include the Angular version within answers so we can track better when it moves to later releases.
請(qǐng)?jiān)诖鸢钢邪ˋngular版本,以便在移至更高版本時(shí)可以更好地進(jìn)行跟蹤。
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)
一次性設(shè)置 (OneTime Setup)
npm install -g @angular/cli
npm install -g @angular/cli
ng new projectFolder creates a new application
ng new projectFolder創(chuàng)建一個(gè)新的應(yīng)用程序
捆綁步驟 (Bundling Step)
ng build --prod (run in command line when directory is projectFolder)
ng build --prod (當(dāng)目錄為projectFolder時(shí)在命令行中運(yùn)行)
flag prod bundle for production (see the Angular documentation for the list of option included with the production flag).
標(biāo)記prod捆綁包(有關(guān)生產(chǎn)標(biāo)記的選項(xiàng)列表,請(qǐng)參閱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/
捆綁包默認(rèn)生成為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您的應(yīng)用程序捆綁了[大小:151 KB,用于新的Angular CLI應(yīng)用程序?yàn)榭?#xff0c;壓縮為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依賴項(xiàng)(@ angular,RxJS ...)[大小:58 KB,用于新的Angular CLI應(yīng)用程序?yàn)榭?#xff0c;壓縮為17 KB ]。
dist/index.html entry point of your application.
應(yīng)用程序的dist/index.html入口點(diǎn)。
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資產(chǎn)配置復(fù)制的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命令來啟動(dòng)應(yīng)用程序的預(yù)覽,該命令啟動(dòng)本地HTTP服務(wù)器,以便可以使用http:// localhost:4200訪問帶有生產(chǎn)文件的應(yīng)用程序。
For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.
對(duì)于生產(chǎn)用途,必須從您選擇的HTTP服務(wù)器中的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之間的區(qū)別。
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.
據(jù)我了解,BehaviorSubject是一個(gè)隨時(shí)間變化的值(可以訂閱,訂閱者可以接收更新的結(jié)果)。 這似乎與Observable的目的完全相同。
When would you use an Observable vs a BehaviorSubject? Are there benefits to using a BehaviorSubject over an Observable or vice versa?
什么時(shí)候使用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是主題的一種,主題是可觀察的特殊類型,因此您可以像其他任何可觀察對(duì)象一樣訂閱消息。 BehaviorSubject的獨(dú)特功能是:
It needs an initial value as it must always return a value on subscription even if it hasn’t received a next()
它需要一個(gè)初始值,因?yàn)榧词刮词盏絥ext() ,它也必須始終在訂閱時(shí)返回一個(gè)值。
Upon subscription it returns the last value of the subject. A regular observable only triggers when it receives an onnext
訂閱后,它將返回主題的最后一個(gè)值。 常規(guī)可觀察對(duì)象僅在收到onnext時(shí)觸發(fā)
at any point you can retrieve the last value of the subject in a non-observable code using the getValue() method.
在任何時(shí)候,您都可以使用getValue()方法以不可觀察的代碼檢索主題的最后一個(gè)值。
Unique features of a subject compared to an observable are:
與可觀察對(duì)象相比,對(duì)象的獨(dú)特特征是:
- 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. 它不僅是可觀察者,而且是觀察者,因此您除了訂閱它之外,還可以將值發(fā)送給主題。
In addition you can get an observable from behavior subject using the asobservable() method on BehaviorSubject.
另外,您可以使用BehaviorSubject上的asobservable()方法從行為主體獲取可觀察對(duì)象。
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.
Observable是泛型,而BehaviorSubject從技術(shù)上講是Observable的子類型,因?yàn)锽ehaviorSubject是具有特定質(zhì)量的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 dExample 2 with regular subject:
例2包含常規(guī)主題:
// 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 dAn 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創(chuàng)建可觀察對(duì)象。 唯一的區(qū)別是您無(wú)法使用next()方法將值發(fā)送給可觀察對(duì)象。
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服務(wù)中,我將對(duì)數(shù)據(jù)服務(wù)使用BehaviorSubject,因?yàn)橛薪嵌鹊姆?wù)通常在組件和行為主體確保使用該服務(wù)的組件接收到最后更新的數(shù)據(jù)之前就進(jìn)行初始化,即使自組件訂閱該數(shù)據(jù)以來沒有新的更新也是如此。
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什么區(qū)別? 他們兩個(gè)似乎完成相同的任務(wù),并具有相同的屬性。
What are the use cases and when to prefer one over another?
用例是什么?何時(shí)優(yōu)先使用一個(gè)?
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'選項(xiàng)restrict: 'A' (指令不限于屬性用法。)指令將行為添加到現(xiàn)有DOM元素或現(xiàn)有組件實(shí)例中。 指令的一個(gè)示例用例是記錄對(duì)元素的單擊。
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:
組件實(shí)際上是在創(chuàng)建自己的具有附加行為的視圖(DOM元素的層次結(jié)構(gòu)),而不是添加/修改行為。 一個(gè)示例用例可能是聯(lián)系卡組件:
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組件,我們可以在應(yīng)用程序中的任何位置使用它,甚至可以在其他組件中使用。 這些基本上構(gòu)成了我們應(yīng)用程序的UI構(gòu)建塊。
綜上所述 (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.
當(dāng)您要?jiǎng)?chuàng)建具有自定義行為的UI的可重用的DOM元素集時(shí),請(qǐng)編寫組件。 當(dāng)您要編寫可重用的行為以補(bǔ)充現(xiàn)有DOM元素時(shí),請(qǐng)編寫指令。
Sources:
資料來源:
@Directive documentation
@Directive文檔
@Component documentation
@Component文檔
Helpful blog post
有用的博客文章
SourceTop
來源 頂部
帶有TypeScript錯(cuò)誤http.get(…).map的角度HTTP GET不是[null]中的函數(shù) (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一個(gè)JSON列表并將其顯示在視圖中。
服務(wù)等級(jí) (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我從服務(wù)中調(diào)用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:
但是,我有一個(gè)例外:
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{}應(yīng)用組件 (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:
我認(rèn)為您需要導(dǎo)入以下內(nèi)容:
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.
或更籠統(tǒng)地說,如果您想擁有更多可觀察的方法。 警告:這將導(dǎo)入所有50多個(gè)運(yùn)算符,并將它們添加到您的應(yīng)用程序中,從而影響捆綁包的大小和加載時(shí)間。
import 'rxjs/Rx';See this issue for more details.
有關(guān)更多詳細(xì)信息,請(qǐng)參見此問題 。
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?
誰(shuí)能告訴我,如何在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.
我知道有一些變通方法,例如預(yù)先處理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 --saveTypescriptDefinitions are not required since you could just use any as the type for $ or jQuery
因?yàn)槟憧梢灾皇褂肨ypescriptDefinitions不需要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.
在您的角度組件中,您應(yīng)該使用@ViewChild()引用模板中的DOM元素。初始化視圖之后,您可以使用此對(duì)象的nativeElement屬性并傳遞給jQuery。
Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.
將$ (或jQuery )聲明為JQueryStatic將為您提供對(duì)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會(huì)抱怨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應(yīng)用中。 我究竟做錯(cuò)了什么?
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
導(dǎo)入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:
理想情況下,您可以將此代碼分成兩個(gè)單獨(dú)的文件。 有關(guān)更多信息,請(qǐng)閱讀:
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
來源 頂部
無(wú)法綁定到“ formGroup”,因?yàn)樗皇恰?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.
請(qǐng)幫忙! 我正在嘗試使Angular2應(yīng)用程序中的表單變得非常簡(jiǎn)單,但是不管它永遠(yuǎn)無(wú)法工作。
ANGULAR VERSION:
角版本:
Angular 2.0.0 Rc5
角2.0.0 Rc5
THE ERROR:
錯(cuò)誤:
Can't bind to 'formGroup' since it isn't a known property of 'form'THE CODE:
代碼:
The view:
風(fēng)景:
<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?
為什么會(huì)出現(xiàn)該錯(cuò)誤?
Am I missing something?
我想念什么嗎?
Stefan Svrkota answered, (465+ points)
Stefan Svrkota 回答了,(465分以上)
RC5 FIX
RC5修復(fù)
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.
解決此問題之后,您可能會(huì)遇到另一個(gè)錯(cuò)誤,因?yàn)闆]有將formControlName="name"添加到表單的輸入中。
RC6/RC7/Final release FIX
RC6 / RC7 /最終發(fā)行版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:
要解決此錯(cuò)誤,您只需要從模塊中的@angular/forms導(dǎo)入ReactiveFormsModule 。 這是帶有ReactiveFormsModule導(dǎo)入的基本模塊的示例:
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.
為了進(jìn)一步說明, formGroup是名為FormGroupDirective指令的選擇器,該指令是ReactiveFormsModule的一部分,因此需要導(dǎo)入它。 它用于將現(xiàn)有的FormGroup綁定到DOM元素。 您可以在Angular的官方文檔頁(yè)面上了解有關(guān)它的更多信息。
SourceTop
來源 頂部
角度DI錯(cuò)誤—例外:無(wú)法解析所有參數(shù) (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.
我已經(jīng)在Angular中構(gòu)建了一個(gè)基本應(yīng)用程序,但是遇到一個(gè)奇怪的問題,即我無(wú)法將服務(wù)注入我的組件之一。 但是,它可以很好地注入我創(chuàng)建的其他三個(gè)組件中的任何一個(gè)。
For starters, this is the service:
對(duì)于初學(xué)者,這是服務(wù):
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:
我在瀏覽器控制臺(tái)中遇到的錯(cuò)誤是這樣的:
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.
我在引導(dǎo)功能中具有該服務(wù),因此它具有提供程序。 而且我似乎可以將其注入到其他任何組件的構(gòu)造函數(shù)中,而不會(huì)出現(xiàn)問題。
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.
從直接聲明的文件而不是桶中導(dǎo)入它。
I don’t know what exactly causes the issue but I saw it mentioned several times (probably some kind of circular dependency).
我不知道是什么導(dǎo)致問題的確切原因,但是我多次提到它(可能是某種循環(huán)依賴)。
It should also be fixable by changing the order of the exports in the barrel (don’t know details, but was mentioned as well)
還應(yīng)該通過更改桶中出口的順序來固定(不知道細(xì)節(jié),但也有人提到)
SourceTop
來源 頂部
Angular —為每個(gè)請(qǐng)求設(shè)置標(biāo)題 (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.
對(duì)于每個(gè)后續(xù)請(qǐng)求,我需要在用戶登錄后設(shè)置一些Authorization標(biāo)頭。
To set headers for a particular request,
要為特定請(qǐng)求設(shè)置標(biāo)題,
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 responseReference
參考
But it would be not be feasible to manually set request headers for every request in this way.
但是以這種方式為每個(gè)請(qǐng)求手動(dòng)設(shè)置請(qǐng)求標(biāo)頭是不可行的。
How do I set the headers set once the user has logged in, and also remove those headers on logout?
用戶登錄后如何設(shè)置標(biāo)頭集,并在注銷時(shí)也刪除這些標(biāo)頭?
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.
要回答這個(gè)問題,您是否可以提供包裝來自Angular的原始Http對(duì)象的服務(wù)。 如下所述。
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對(duì)象,您可以注入這個(gè)對(duì)象( 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.
我也覺得這事可以采用多供應(yīng)商的做Http通過提供擴(kuò)展自己的類類Http一個(gè)...查看此鏈接: 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實(shí)現(xiàn)相同的行為?
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獨(dú)自:
<div *ngIf="isValid;then content"></div><ng-template #content>content here...</ng-template>Demo :
演示:
Plunker
柱塞
Details:
細(xì)節(jié):
<ng-template> : is Angular’s own implementation of the <template> tag which is according to MDN :
<ng-template> :是Angular自己根據(jù)MDN實(shí)現(xiàn)的<template>標(biāo)簽的實(shí)現(xiàn):
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組件時(shí)遇到問題。 我試圖解決很長(zhǎng)時(shí)間,甚至試圖將其添加到單個(gè)文件中。 我所擁有的是:
Application.ts
應(yīng)用程序
/// <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” …
我一直在收到錯(cuò)誤消息,說“沒有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中的對(duì)象 (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+個(gè)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元素綁定到對(duì)象列表-這很容易:
@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將是一個(gè)數(shù)字-所選項(xiàng)目的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:
但是,我實(shí)際上想綁定到country對(duì)象本身,以便selectedValue是對(duì)象,而不僅僅是id。 我試圖像這樣更改選項(xiàng)的值:
<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中放置了一個(gè)對(duì)象—但不是我期望的對(duì)象。 您可以在我的Plunker示例中看到這一點(diǎn) 。
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事件,以便可以根據(jù)所選的id自己設(shè)置對(duì)象; 但是,似乎更改事件在綁定的ngModel更新之前觸發(fā)-這意味著我當(dāng)時(shí)無(wú)法訪問新選擇的值。
Is there a clean way to bind a select element to an object with Angular 2?
有沒有一種干凈的方法可以將選擇元素綁定到帶有Angular 2的對(duì)象?
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是完整的國(guó)家對(duì)象。
[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是一個(gè)對(duì)象,則預(yù)選實(shí)例必須與其中一個(gè)值相同。
See also the recently added custom comparison https://github.com/angular/angular/issues/13268 available since 4.0.0-beta.7
另請(qǐng)參閱自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.
請(qǐng)注意是否要在compareFn訪問this 。
compareFn = this._compareFn.bind(this);// or // compareFn = (a, b) => this._compareFn(a, b);_comareFn((a, b) {if(this.x ...) {... }SourceTop
來源 頂部
NgModule中的聲明,提供程序和導(dǎo)入之間有什么區(qū)別 (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(有時(shí)稱為Angular2 +),然后遇到了@Module
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使其他模塊的導(dǎo)出聲明在當(dāng)前模塊中可用
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將使當(dāng)前模塊中的指令(包括組件和管道)可用于當(dāng)前模塊中的其他指令。 指令,組件或管道的選擇器只有在聲明或?qū)霑r(shí)才與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者應(yīng)使DI知道服務(wù)和價(jià)值。 它們被添加到根范圍,并且被注入到其他具有它們依賴關(guān)系的服務(wù)或指令中。
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延遲加載模塊的僅提供給默認(rèn)此延遲加載模塊(未整個(gè)應(yīng)用程序,因?yàn)樗c其他模塊)。
For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html
有關(guān)模塊的更多詳細(xì)信息,另請(qǐng)參見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使模塊中的組件,指令和管道可用,從而將該模塊添加到imports 。 exports還可以用于重新導(dǎo)出諸如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注冊(cè)用于脫機(jī)編譯的組件,以便它們可以與ViewContainerRef.createComponent()一起使用。 路由器配置中使用的組件是隱式添加的。
TypeScript (ES2015) imports
TypeScript(ES2015)導(dǎo)入
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導(dǎo)入。 每當(dāng)在另一個(gè)打字稿文件中聲明的打字稿文件中使用標(biāo)識(shí)符時(shí),都需要這些。
Angular’s @NgModule() imports and TypeScript import are entirely different concepts.
Angular的@NgModule() imports和TypeScript import是完全不同的概念 。
See also jDriven — TypeScript and ES6 import syntax
另請(qǐng)參見jDriven — TypeScript和ES6導(dǎo)入語(yǔ)法
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中,如何確定活動(dòng)路線? (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.
注意: 這里有很多不同的答案,大多數(shù)答案一次或一次都有效。 事實(shí)是,隨著Angular團(tuán)隊(duì)更改了路由器,有效的方法已經(jīng)改變了很多次。 最終將成為 Angular路由器的Router 3.0版本打破了許多解決方案,但提供了一個(gè)非常簡(jiǎn)單的解決方案。 從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應(yīng)用程序中(我撰寫本文時(shí)為2.0.0-beta.0版本中的當(dāng)前版本),如何確定當(dāng)前活動(dòng)的路由是什么?
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.
我正在開發(fā)一個(gè)使用Bootstrap 4的應(yīng)用程序,當(dāng)在<router-outp ut>標(biāo)簽中顯示其關(guān)聯(lián)組件時(shí),我需要一種方法來將導(dǎo)航鏈接/按鈕標(biāo)記為活動(dòng)狀態(tài)。
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).
我意識(shí)到當(dāng)單擊其中一個(gè)按鈕時(shí),我可以自己維護(hù)狀態(tài),但是這不會(huì)涉及將多條路徑放入同一條路線的情況(例如主導(dǎo)航菜單以及主組件中的本地菜單) )。
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:
或者,如果只需要一個(gè)類,則為簡(jiǎn)化的非數(shù)組格式:
<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.)
有關(guān)更多信息,請(qǐng)參見文檔文獻(xiàn)不routerLinkActive指令 。 (我主要是通過反復(fù)試驗(yàn)弄清楚這一點(diǎn)。)
UPDATE: Better documentation for the routerLinkActive directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)
更新:現(xiàn)在可以在此處找到更好的關(guān)于routerLinkActive指令的文檔。 (感謝@Victor Hugo Arango A.在下面的評(píng)論中。)
SourceTop
來源 頂部
Angular CLI SASS選項(xiàng) (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社區(qū)。 嘗試使用基于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項(xiàng)目中處理SASS的最佳方法。 我嘗試使用ember-cli-sass庫(kù)來查看它是否可以正常運(yùn)行,因?yàn)锳ngular-CLI的許多核心組件都使用了Ember-CLI模塊。
It didnt work but than again not sure if I just misconfigured something.
它沒有用,但還是不確定我是否配置錯(cuò)誤。
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項(xiàng)目中組織樣式的最佳方法是什么? 最好將sass文件與組件放在同一文件夾中。
Mertcan Diken answered, (323+ points)
Mertcan Diken 回答了,(323分以上)
When you are creating your project with angular cli try this:
當(dāng)您使用angular cli創(chuàng)建項(xiàng)目時(shí),請(qǐng)嘗試以下操作:
ng new My_New_Project --style=sassThis generating all your components with predifined sass files.
這將生成帶有預(yù)定義sass文件的所有組件。
If you want scss syntax create your project with :
如果要使用scss語(yǔ)法,請(qǐng)使用以下命令創(chuàng)建項(xiàng)目:
ng new My_New_Project --style=scssIf you are changing your existing style in your project
如果您要更改項(xiàng)目中的現(xiàn)有樣式
ng set defaults.styleExt scssCli 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?
我究竟做錯(cuò)了什么?
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/lodashThen, 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?
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.
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.
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. 在下面的更多內(nèi)容。
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?
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.
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.6The 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.
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/
https://www.npmjs.com/~types
https://www.npmjs.com/~types
Install Example:
Install Example:
npm install --save-dev @types/core-jsDuplicate 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+ :
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 }
Documentation Links: ngOnChanges, SimpleChanges, SimpleChange
Documentation Links: ngOnChanges, SimpleChanges, SimpleChange
Demo Example: Look at
Demo Example: Look at
this plunker
this plunker
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; }
Documentation Link: Look here.
Documentation Link: Look here .
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.
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 .
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:
一個(gè)例子:
// 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:
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
Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property (Angular2 Exception: Can’t bind to ‘routerLink’ since it isn’t a known native property)
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.htmlWith 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:11I 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:
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.
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(), ... ], ... })
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" ],
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</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 --savethen 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?
我究竟做錯(cuò)了什么?
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:
npm install font-awesome --save
npm install font-awesome --save
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!? ], … } ] ]
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>
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.
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面試題及答案
總結(jié)
以上是生活随笔為你收集整理的angular面试题及答案_关于最流行的Angular问题的StackOverflow上的48个答案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到掉水里了什么意思周公解梦
- 下一篇: 梦到鞋底烂了预示着什么