angular面试题及答案

by Shlomi Levi

通过Shlomi Levi

关于最流行的Angular问题的StackOverflow上的48个答案 (48 answers on StackOverflow to the most popular Angular questions)

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

我从Stackoverflow收集了最常见的问题和解答。 这些问题是根据获得的最高分数来选择的。 无论您是专家还是初学者,都可以从他人的经验中学到东西。

目录 (Table of Contents)

  • Angular — Promise vs Observable

    角度—承诺与可观察

  • Difference between Constructor and ngOnInit

    构造函数和ngOnInit之间的区别

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

    无法绑定到“ ngModel”,因为它不是“ input”的已知属性

  • Angular HTML binding

    角度HTML绑定

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

    Angular / RxJs我应该何时退订`Subscription`

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

    如何在组件模板中选择元素?

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

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

  • How to bundle an Angular app for production

    如何捆绑Angular应用进行生产

  • BehaviorSubject vs Observable?

    BehaviorSubject与Observable?

  • @Directive v/s @Component in Angular

    @Directive v / s @Component在Angular中

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

    带有TypeScript错误http.get(…).map的角度HTTP GET不是[null]中的函数

  • How to use jQuery with Angular?

    如何在Angular中使用jQuery?

  • Angular EXCEPTION: No provider for Http

    Angular EXCEPTION:没有Http的提供程序

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

    无法绑定到“ formGroup”,因为它不是“ form”的已知属性

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

    角度DI错误—例外:无法解析所有参数

  • Angular — Set headers for every request

    Angular —为每个请求设置标题

  • How to use *ngIf else in Angular?

    如何在Angular中使用* ngIf else?

  • Angular no provider for NameService

    Angular没有NameService提供程序

  • Binding select element to object in Angular

    将选择元素绑定到Angular中的对象

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

    NgModule中的声明,提供程序和导入之间有什么区别

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

    在Angular中,如何确定活动路线?

  • Angular CLI SASS options

    Angular CLI SASS选项

  • Triggering change detection manually in Angular

    在Angular中手动触发变化检测

  • Angular and Typescript: Can’t find names

    Angular和Typescript:找不到名称

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

    角度—组件中module.id的含义是什么?

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

    如何在Angular 2的“选择”中获得新选择?

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

    角度异常:无法绑定到“ ngForIn”,因为它不是已知的本机属性

  • *ngIf and *ngFor on same element causing error

    * ngIf和* ngFor在同一元素上导致错误

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

    Angular等效于AngularJS $ watch?

  • Importing lodash into angular2 + typescript application

    将lodash导入angular2 +打字稿应用程序

  • How to detect a route change in Angular?

    如何在Angular中检测路线变化?

  • Global Events in Angular

    Angular中的全球事件

  • What are differences between SystemJS and Webpack?

    SystemJS和Webpack有什么区别?

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

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

  • Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0

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

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

    如何检测Angular中@Input()值何时更改?

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

    如何将url参数(查询字符串)传递给Angular上的HTTP请求

  • How do you deploy Angular apps?

    您如何部署Angular应用程序?

  • ngFor with index as value in attribute

    ngFor,其中索引作为属性中的值

  • Define global constants in Angular 2

    在Angular 2中定义全局常量

  • Angular — Use pipes in services and components

    角度—在服务和组件中使用管道

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

    Angular2异常:由于它不是已知的本机属性,因此无法绑定到“ routerLink”

  • Angular 2 dynamic tabs with user-click chosen components

    带有用户单击所选组件的Angular 2动态选项卡

  • Delegation: EventEmitter or Observable in Angular

    委托:EventEmitter或可观察到的Angular

  • How to add bootstrap to an angular-cli project

    如何将引导程序添加到angular-cli项目

  • access key and value of object using *ngFor

    使用* ngFor访问对象的键和值

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

    角度异常:无法绑定到“ ngFor”,因为它不是已知的本机属性

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

    如何将真棒字体添加到Angular 2 + CLI项目

  • Difference between HTTP and HTTPClient in angular 4?

    HTTP和HTTPClient在角度4中的区别?

Enjoy!

请享用!

角度—承诺与可观察 (Angular — Promise vs Observable)

551+ points ? 150,497+ viewed

551+分 已查看1 50,497+

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

551+分 罗希特(Rohit)问过 1 50,497+次观看

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

有人可以解释Angular中PromiseObservable之间的区别吗?

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

每个示例均有助于理解这两种情况。 在什么情况下我们可以使用每种情况?

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

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

Promise

诺言

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

当异步操作完成或失败时, Promise处理单个事件

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

注意:那里有Promise库支持取消,但是ES6 Promise到目前为止还不支持。

Observable

可观察的

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

一个Observable就像一个Stream (在许多语言中),并且允许传递零个或多个事件,其中每个事件都被调用回调。

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

通常, ObservablePromise更为可取,因为它提供了Promise等功能。 使用Observable ,您要处理0、1或多个事件都没有关系。 在每种情况下,您都可以使用相同的API。

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

Promise相比, Observable也具有可取消的优势。 如果不再需要对服务器的HTTP请求或其他昂贵的异步操作的结果,则ObservableSubscription可以取消该预订,而Promise最终将调用成功或失败的回调,即使您不需要需要通知或它提供的结果了。

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

Observable提供类似于mapforEachreduce ,...的运算符 ,类似于数组

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

还有一些功能强大的运算符,例如retry()replay() ……通常非常方便。

SourceTop

来源 顶部

构造函数和ngOnInit之间的区别 (Difference between Constructor and ngOnInit)

444+ points ? 190,166+ viewed

444+分 已查看1 90,166+

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

444+分 已查看1 90166则以上Haseena PA的问题,

Angular provides lifecycle hook ngOnInit by default.

Angular默认提供生命周期挂钩ngOnInit

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

如果我们已经有了constructor ,为什么还要使用ngOnInit呢?

Pardeep Jain answered, (512+ points)

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

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

Constructor是该类的默认方法,该方法在实例化该类时执行,并确保该类及其子类中字段的正确初始化。 有角或更好的依赖注入器(DI)分析构造函数参数,并在通过调用new MyClass()创建新实例时尝试寻找与构造函数参数类型匹配的提供程序,将其解析并将其传递给构造函数,例如

new MyClass(someArg);

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

ngOnInitngOnInit调用的生命周期挂钩,以指示Angular已完成创建组件。

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

我们必须导入OnInit才能这样使用(实际上,强制实施OnInit不是强制性的,但被认为是好的做法):

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

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

然后要使用OnInit的方法,我们必须在此类中实现。

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

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

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

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

通常,我们将ngOnInit用于所有的初始化/声明,并避免在构造函数中起作用。 构造函数应仅用于初始化类成员,而不应执行实际的“工作”。

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

因此,您应该使用constructor()来设置依赖注入,而无需过多设置。 ngOnInit()是“开始”的更好位置-解析组件绑定的位置/位置。

For more information refer here:

有关更多信息,请参见此处:

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

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

  • Angular 2 Component Constructor Vs OnInit

    Angular 2组件构造函数与OnInit

SourceTop

来源 顶部

无法绑定到“ ngModel”,因为它不是“ input”的已知属性 (Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’)

442+ points ? 246,901+ viewed

442+点 已查看2 46,901+

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

442+点 2 46,901+浏览过abreneliere询问,

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

即使未显示组件,启动我的Angular应用程序时也会出现以下错误。

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

我必须注释掉,这样我的应用才能正常工作。

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

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

我在看英雄拔毛器,但没什么区别。

Here is the component file:

这是组件文件:

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

abreneliere answered, (674+ points)

abreneliere 回答了,(674+分)

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

是的就是这样,在app.module.ts中,我刚刚添加了:

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

SourceTop

来源 顶部

角度HTML绑定 (Angular HTML binding)

385+ points ? 227,115+ viewed

385+分 已查看2 27,115+

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

385+分 2 27,115+查看过Aviad P.问,

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

我正在编写Angular应用程序,并且要显示HTML响应。 我怎么做? 如果我仅使用绑定语法{{myVal}}它将对所有HTML字符进行编码(当然)。

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

我需要以某种方式将div的内部html绑定到变量值。

prolink007 answered, (691+ points)

prolink007 回答,(超过691分)

The correct syntax is now the following:

现在,正确的语法如下:

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

Working in 5.2.6

5.2.6工作

Documentation Reference

文档参考

SourceTop

来源 顶部

Angular / RxJs我应该何时退订`Subscription` (Angular/RxJs When should I unsubscribe from `Subscription`)

320+ points ? 69,606+ viewed

320+分 已查看6 9,606+

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

320+分 6 9,606+浏览过Sergey Tihon 问,

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

我应该何时在NgOnDestroy生命周期中存储Subscription实例并调用unsubscribe() ,何时可以忽略它们?

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

保存所有订阅会在组件代码中带来很多麻烦。

HTTP Client Guide ignore subscriptions like this:

HTTP客户端指南会忽略这样的订阅:

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

In the same time Route & Navigation Guide says that:

同时,《 路线与导航指南 》指出:

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

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

We unsubscribe from our Observable in the ngOnDestroy method.

We unsubscribe from our Observable in the ngOnDestroy method.

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

seangwright answered, (508+ points)

seangwright 回答,(超过508分)

— —编辑3 —“官方”解决方案(2017/04/09) (— — Edit 3 — The ‘Official’ Solution (2017/04/09))

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

我在NGConf上与Ward Bell谈到了这个问题(我什至向他展示了这个答案,他说的是正确的),但是他告诉我Angular的文档小组对这个问题的解决方案尚未发布(尽管他们正在努力使其获得批准) )。 他还告诉我,我可以通过即将提出的官方建议来更新我的SO答案。

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

今后我们应该使用的解决方案是添加一个private ngUnsubscribe: Subject = new Subject(); 所有在其类代码中具有.subscribe()调用Observable的组件的字段。

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

然后,我们将其称为this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); 在我们的ngOnDestroy()方法中。

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

秘诀(如@metamaker所述 )是在我们的每个.subscribe()调用之前调用.takeUntil(this.ngUnsubscribe) ,这将确保在销毁组件时清除所有订阅。

Example:

例:

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

-编辑2(2016/12/28) (— — Edit 2 (2016/12/28))

Source 5

来源5

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

Angular教程的“路由”一章现在指出以下内容:“路由器管理它提供的可观察对象并本地化订阅。 当组件被销毁时,订阅将被清除,以防止内存泄漏,因此我们无需取消订阅可观察到的路由参数。” — 马克·拉杰克 ( Mark Rajcok)

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

这是针对有关Router Observables的Angular文档的Github问题的讨论 ,Ward Bell提到正在为所有这些澄清。

— —编辑1 (— — Edit 1)

Source 4

来源4

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

在NgEurope的这段视频中, Rob Wormald还说您不需要取消订阅Router Observables。 他还在2016年11月的视频中提到了http服务和ActivatedRoute.params

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

TLDR:

TLDR:

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

对于此问题,有(2)种Observables值- 有限值和无限值。

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

http Observables产生有限 (1)值,类似DOM event listener东西Observables产生无限值。

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

如果您手动调用subscribe (不使用异步管道),则unsubscribe 无限的 Observables

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

不必担心有限RxJs会照顾他们。

Source 1

来源1

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

我在这里从Angular的Gitter中找到了 Rob Wormald的答案。

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

他指出(为清晰起见,我进行了重组,重点是我的)

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

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

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

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

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

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

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

他还在YouTube上有关Observables的视频中提到, they clean up after themselves ……在complete的Observables的背景下(例如Promises,由于它们总是产生1值并结束,所以它们总是完成的-我们从不担心从Promises退订到确保他们清理了xhr事件监听器,对吧?)。

Source 2

来源2

Also in the Rangle guide to Angular 2 it reads

同样在Angular 2的Rangle指南中

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

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

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

什么时候our Observable has a longer lifespan than our subscription短语our Observable has a longer lifespan than our subscription

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

它适用于在组件内部创建预订,而该组件在Observable完成之前被销毁(或未“长久”)的情况。

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

我的意思是,如果我们订阅一个http请求或一个发出10个值的Observable,并且在该http请求返回或发出10个值之前销毁了我们的组件,我们还是可以的!

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

当请求确实返回或最终发出第十个值时, Observable将完成,所有资源将被清理。

Source 3

来源3

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

如果我们从相同的Rangle指南中查看此示例 ,则可以看到对route.paramsSubscription确实需要unsubscribe()因为我们不知道这些params何时会停止更改(发出新值)。

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

通过导航可以破坏该组件,在这种情况下,路由参数可能仍会更改(它们可能会在技术上更改,直到应用程序结束),并且由于尚未completion因此仍将分配订阅中分配的资源。

SourceTop

来源 顶部

如何在组件模板中选择元素? (How can I select an element in a component template?)

263+ points ? 265,966+ viewed

263+分 已查看2 65,966+

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

263+分 2 65,966+浏览过Aman Gupta问,

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

有人知道如何掌握组件模板中定义的元素吗? 使用$$$可以使Polymer变得非常容易。

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

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

Take the example from the tutorial:

从教程中获取示例:

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

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

如何从类定义中抓住对pinput元素的引用?

Brocco answered, (149+ points)

布罗科 (149)

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

您可以通过将ElementRef注入到组件的构造函数中来通过ElementRef获取DOM元素的句柄:

constructor(myElement: ElementRef) { ... }

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

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

SourceTop

来源 顶部

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

261+ points ? 206,651+ viewed

261+分 已查看2 06,651+

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

261+分 2 06,651+浏览了MihaiRăducanu 问,

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

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

In AngularJS I would write

在AngularJS中,我会写

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

How can I do this in Angular?

如何在Angular中做到这一点?

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

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

Just bind to the hidden property

只需绑定到hidden属性

[hidden]="!myVar"

See also

也可以看看

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

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

issues

问题

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

hidden有一些问题,因为它可能与display属性CSS冲突。

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

看看在Plunker示例中如何隐藏some样式,因为它具有样式

:host {display: block;}

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

组。 (这在其他浏览器中可能会有所不同-我在Chrome 50上进行了测试)

workaround

解决方法

You can fix it by adding

您可以通过添加来修复它

[hidden] { display: none !important;}

To a global style in index.html.

index.html的全局样式。

another pitfall

另一个陷阱

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

are the same as

与...相同

hidden="true"

and will not show the element.

并且不会显示该元素。

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

hidden="false"将分配被认为是真实的字符串"false"只有值false或删除属性才能使该元素可见。

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

使用{{}}还会将表达式转换为字符串,将无法正常工作。

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

只有与[]绑定才能按预期工作,因为此false被分配为false而不是"false"

*ngIf vs [hidden]

*ngIf [hidden]

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

*ngIf有效地从DOM中删除了它的内容,而[hidden]修改了display属性,仅指示浏览器不显示内容,但DOM仍然包含它。

SourceTop

来源 顶部

如何捆绑Angular应用进行生产 (How to bundle an Angular app for production)

258+ points ? 111,603+ viewed

258+分 已查看1 11,603+

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

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

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

我想在此线程中跟踪和更新最新的最佳(也是最简单的)方法,以便将Angular(版本2、4…)捆绑在一起,以在实时Web服务器上进行生产。

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

请在答案中包括Angular版本,以便在移至更高版本时可以更好地进行跟踪。

Nicolas Henneaux answered, (267+ points)

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

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

一次性设置 (OneTime Setup)

  • npm install -g @angular/cli

    npm install -g @angular/cli

  • ng new projectFolder creates a new application

    ng new projectFolder创建一个新的应用程序

捆绑步骤 (Bundling Step)

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

    ng build --prod (当目录为projectFolder时在命令行中运行)

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

    标记prod捆绑包(有关生产标记的选项列表,请参阅Angular文档 )。

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

    使用Brotli压缩 , for i in dist/*; do brotli $i; done使用以下命令压缩资源for i in dist/*; do brotli $i; done for i in dist/*; do brotli $i; done

bundles are generated by default to projectFolder/dist/

捆绑包默认生成为projectFolder / dist /

输出量 (Output)

Sizes with Angular 5.2.8 with CLI 1.7.2

带有CLI 1.7.2 Angular 5.2.8大小

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

    dist/main.[hash].bundle.js您的应用程序捆绑了[大小:151 KB,用于新的Angular CLI应用程序为空,压缩为36 KB ]。

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

    dist/polyfill.[hash].bundle.js捆绑了polyfill依赖项(@ angular,RxJS ...)[大小:58 KB,用于新的Angular CLI应用程序为空,压缩为17 KB ]。

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

    应用程序的dist/index.html入口点。

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

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

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

    dist/style.[hash].bundle.css样式定义

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

    从Angular CLI资产配置复制的dist/assets资源

部署方式 (Deployment)

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

您可以使用ng serve --prod命令来启动应用程序的预览,该命令启动本地HTTP服务器,以便可以使用http:// localhost:4200访问带有生产文件的应用程序。

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

对于生产用途,必须从您选择的HTTP服务器中的dist文件夹中部署所有文件。

SourceTop

来源 顶部

BehaviorSubject与Observable? (BehaviorSubject vs Observable?)

250+ points ? 122,248+ viewed

250+分 已查看1 22,248+

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

250+分 1 22,248+浏览了Kevin Mark问,

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

我正在研究Angular RxJs模式,但我不了解BehaviorSubject和Observable之间的区别。

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

据我了解,BehaviorSubject是一个随时间变化的值(可以订阅,订阅者可以接收更新的结果)。 这似乎与Observable的目的完全相同。

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

什么时候使用Observable与BehaviorSubject? 在Observable上使用BehaviorSubject有好处,反之亦然吗?

Shantanu Bhadoria answered, (425+ points)

Shantanu Bhadoria 回答了,(425+分)

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

BehaviorSubject是主题的一种,主题是可观察的特殊类型,因此您可以像其他任何可观察对象一样订阅消息。 BehaviorSubject的独特功能是:

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

    它需要一个初始值,因为即使未收到next() ,它也必须始终在订阅时返回一个值。

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

    订阅后,它将返回主题的最后一个值。 常规可观察对象仅在收到onnext时触发

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

    在任何时候,您都可以使用getValue()方法以不可观察的代码检索主题的最后一个值。

Unique features of a subject compared to an observable are:

与可观察对象相比,对象的独特特征是:

  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.它不仅是可观察者,而且是观察者,因此您除了订阅它之外,还可以将值发送给主题。

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

另外,您可以使用BehaviorSubject上的asobservable()方法从行为主体获取可观察对象。

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

Observable是泛型,而BehaviorSubject从技术上讲是Observable的子类型,因为BehaviorSubject是具有特定质量的Observable。

Example with BehaviorSubject:

BehaviorSubject的示例:

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

Example 2 with regular subject:

例2包含常规主题:

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

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

可以使用subject.asobservable()从Subject和BehaviorSubject创建可观察对象。 唯一的区别是您无法使用next()方法将值发送给可观察对象。

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

在Angular服务中,我将对数据服务使用BehaviorSubject,因为有角度的服务通常在组件和行为主体确保使用该服务的组件接收到最后更新的数据之前就进行初始化,即使自组件订阅该数据以来没有新的更新也是如此。

SourceTop

来源 顶部

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

239+ points ? 61,582+ viewed

239+分 查看了6 1,582+

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

239+分 6 1,582+浏览过的Prasanjit Dey 问,

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

Angular中@Component@Directive什么区别? 他们两个似乎完成相同的任务,并具有相同的属性。

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

用例是什么?何时优先使用一个?

jaker answered, (327+ points)

杰克 回答,(超过327分)

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

@Component需要视图,而@Directive则不需要。

指令 (Directives)

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

我将@Directive比作Angular 1.0指令,并带有restrict: 'A'选项restrict: 'A' (指令不限于属性用法。)指令将行为添加到现有DOM元素或现有组件实例中。 指令的一个示例用例是记录对元素的单击。

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

Which would be used like so:

可以这样使用:

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

组件 (Components)

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

组件实际上是在创建自己的具有附加行为的视图(DOM元素的层次结构),而不是添加/修改行为。 一个示例用例可能是联系卡组件:

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

Which would be used like so:

可以这样使用:

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

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

ContactCard是可重用的UI组件,我们可以在应用程序中的任何位置使用它,甚至可以在其他组件中使用。 这些基本上构成了我们应用程序的UI构建块。

综上所述 (In summary)

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

当您要创建具有自定义行为的UI的可重用的DOM元素集时,请编写组件。 当您要编写可重用的行为以补充现有DOM元素时,请编写指令。

Sources:

资料来源:

  • @Directive documentation

    @Directive文档

  • @Component documentation

    @Component文档

  • Helpful blog post

    有用的博客文章

SourceTop

来源 顶部

带有TypeScript错误http.get(…).map的角度HTTP GET不是[null]中的函数 (Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null])

233+ points ? 141,917+ viewed

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

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

233分以上 Claudiu 问了 1 41,917+次观看

I have a problem with HTTP in Angular.

我在Angular中遇到HTTP问题。

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

我只想GET一个JSON列表并将其显示在视图中。

服务等级 (Service class)

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

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

HallListComponent我从服务中调用getHalls方法:

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

However, I got an exception:

但是,我有一个例外:

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

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

霍尔中心组件 (hall-center.component)

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

应用组件 (app.component)

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

tsconfig.json (tsconfig.json)

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

Thierry Templier answered, (416+ points)

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

I think that you need to import this:

我认为您需要导入以下内容:

import 'rxjs/add/operator/map'

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

或更笼统地说,如果您想拥有更多可观察的方法。 警告:这将导入所有50多个运算符,并将它们添加到您的应用程序中,从而影响捆绑包的大小和加载时间。

import 'rxjs/Rx';

See this issue for more details.

有关更多详细信息,请参见此问题 。

SourceTop

来源 顶部

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

233+ points ? 246,869+ viewed

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

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

233分以上 2 46,869+浏览过Waog问,

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

谁能告诉我,如何在Angular中使用jQuery

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

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

我知道有一些变通方法,例如预先处理DOM元素的ID ,但我希望有一种更干净的方法。

werenskjold answered, (258+ points)

Arenskjold 回答了,(258分以上)

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

与ng1相比,使用来自Angular2的jQuery轻而易举。 如果您使用的是TypeScript,则可以先引用jQuery打字稿定义。

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

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

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

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

在您的角度组件中,您应该使用@ViewChild()引用模板中的DOM元素。初始化视图之后,您可以使用此对象的nativeElement属性并传递给jQuery。

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

$ (或jQuery )声明为JQueryStatic将为您提供对jQuery的类型化引用。

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

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

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

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

tslint会抱怨chosen不是$的属性,要解决此问题,您可以在自定义* .d.ts文件的JQuery接口中添加定义

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

SourceTop

来源 顶部

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

230+ points ? 142,976+ viewed

230+分 已查看1 42,976+

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

230+分 1 42976+观看过的丹尼尔问,

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

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

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

Philip Miglinci answered, (381+ points)

Philip Miglinci 回答,(超过381分)

Import the HttpModule

导入HttpModule

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

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

理想情况下,您可以将此代码分成两个单独的文件。 有关更多信息,请阅读:

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

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

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

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

SourceTop

来源 顶部

无法绑定到“ formGroup”,因为它不是“ form”的已知属性 (Can’t bind to ‘formGroup’ since it isn’t a known property of ‘form’)

227+ points ? 127,130+ viewed

227+分 已查看1 27,130+

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

227+分 观看 1 27,130+次johnnyfittizio问,

THE SITUATION:

情况:

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

请帮忙! 我正在尝试使Angular2应用程序中的表单变得非常简单,但是不管它永远无法工作。

ANGULAR VERSION:

角版本:

Angular 2.0.0 Rc5

角2.0.0 Rc5

THE ERROR:

错误:

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

THE CODE:

代码:

The view:

风景:

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

The controller:

控制器:

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

The ngModule:

ngModule:

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

THE QUESTION:

问题:

Why am I getting that error?

为什么会出现该错误?

Am I missing something?

我想念什么吗?

Stefan Svrkota answered, (465+ points)

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

RC5 FIX

RC5修复

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

您需要import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'控制器中的import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'并将其添加到@Component directives中。 这样可以解决问题。

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

解决此问题之后,您可能会遇到另一个错误,因为没有将formControlName="name"添加到表单的输入中。

RC6/RC7/Final release FIX

RC6 / RC7 /最终发行版FIX

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

要解决此错误,您只需要从模块中的@angular/forms导入ReactiveFormsModule 。 这是带有ReactiveFormsModule导入的基本模块的示例:

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

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

为了进一步说明, formGroup是名为FormGroupDirective指令的选择器,该指令是ReactiveFormsModule的一部分,因此需要导入它。 它用于将现有的FormGroup绑定到DOM元素。 您可以在Angular的官方文档页面上了解有关它的更多信息。

SourceTop

来源 顶部

角度DI错误—例外:无法解析所有参数 (Angular DI Error — EXCEPTION: Can’t resolve all parameters)

221+ points ? 142,497+ viewed

221+分 已查看1 42,497+

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

221+分 1 42497+观看过Keith Otto的提问,

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

我已经在Angular中构建了一个基本应用程序,但是遇到一个奇怪的问题,即我无法将服务注入我的组件之一。 但是,它可以很好地注入我创建的其他三个组件中的任何一个。

For starters, this is the service:

对于初学者,这是服务:

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

And the component that it refuses to work with:

以及它拒绝使用的组件:

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

The error I get in the browser console is this:

我在浏览器控制台中遇到的错误是这样的:

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

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

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

我在引导功能中具有该服务,因此它具有提供程序。 而且我似乎可以将其注入到其他任何组件的构造函数中,而不会出现问题。

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

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

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

从直接声明的文件而不是桶中导入它。

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

我不知道是什么导致问题的确切原因,但是我多次提到它(可能是某种循环依赖)。

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

还应该通过更改桶中出口的顺序来固定(不知道细节,但也有人提到)

SourceTop

来源 顶部

Angular —为每个请求设置标题 (Angular — Set headers for every request)

209+ points ? 205,557+ viewed

209+分 已查看2 05,557+

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

209+分 2 05,557+次浏览Avijit Gupta问,

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

对于每个后续请求,我需要在用户登录后设置一些Authorization标头。

To set headers for a particular request,

要为特定请求设置标题,

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

Reference

参考

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

但是以这种方式为每个请求手动设置请求标头是不可行的。

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

用户登录后如何设置标头集,并在注销时也删除这些标头?

Thierry Templier answered, (283+ points)

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

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

要回答这个问题,您是否可以提供包装来自Angular的原始Http对象的服务。 如下所述。

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

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

而不是注入Http对象,您可以注入这个对象( HttpClient )。

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

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

我也觉得这事可以采用多供应商的做Http通过提供扩展自己的类类Http一个...查看此链接: http://blog.thoughtram.io/angular2/2015/11/23/multi -providers-in-angular-2.html 。

SourceTop

来源 顶部

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

205+ points ? 203,768+ viewed

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

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

205分以上 2 03,768+浏览过kawli norman 问,

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

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

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

How can I acheive the same behavior with ngIf else ?

如何使用ngIf else实现相同的行为?

Bougarfaoui El houcine answered, (384+ points)

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

Angular 4 and 5:

角度4和5

using else :

使用else

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

you can also use then else :

您还可以使用then else

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

or then alone :

then独自:

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

Demo :

演示:

Plunker

柱塞

Details:

细节:

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

<ng-template> :是Angular自己根据MDN实现的<template>标签的实现:

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

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

SourceTop

来源 顶部

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

196+ points ? 186,526+ viewed

196+分 已查看1 86,526+

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

196+分 观看了1 86,526+次M.Svrcek的提问,

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

我在将类加载到Angular组件时遇到问题。 我试图解决很长时间,甚至试图将其添加到单个文件中。 我所拥有的是:

Application.ts

应用程序

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

services/NameService.ts

services / NameService.ts

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

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

我一直在收到错误消息,说“没有NameService的提供者”……

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

有人可以帮我找出我的代码中的小问题吗?

Klas Mellbourn answered, (309+ points)

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

You have to use providers instead of injectables

您必须使用providers而不是injectables

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

Complete code sample here.

在此处完成代码示例 。

SourceTop

来源 顶部

将选择元素绑定到Angular中的对象 (Binding select element to object in Angular)

194+ points ? 197,048+ viewed

194+分 已查看1 97,048+

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

194+分 已查看1 97,048+个RHarris的 问题,

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

我是Angular的新手,并试图跟上新的工作方式。

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

我想将select元素绑定到对象列表-这很容易:

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

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

在这种情况下,似乎selectedValue将是一个数字-所选项目的ID。

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

但是,我实际上想绑定到country对象本身,以便selectedValue是对象,而不仅仅是id。 我试图像这样更改选项的值:

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

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

但这似乎不起作用。 似乎在我的selectedValue中放置了一个对象—但不是我期望的对象。 您可以在我的Plunker示例中看到这一点 。

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

我还尝试绑定到change事件,以便可以根据所选的id自己设置对象; 但是,似乎更改事件在绑定的ngModel更新之前触发-这意味着我当时无法访问新选择的值。

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

有没有一种干净的方法可以将选择元素绑定到带有Angular 2的对象?

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

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

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

Plunker example

柱塞示例

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

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

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

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

update

更新

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

如果该value是一个对象,则预选实例必须与其中一个值相同。

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

另请参阅自4.0.0-beta.7起可用的最近添加的自定义比较https://github.com/angular/angular/issues/13268

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

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

请注意是否要在compareFn访问this

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

SourceTop

来源 顶部

NgModule中的声明,提供程序和导入之间有什么区别 (What is difference between declarations, providers and import in NgModule)

188+ points ? 55,432+ viewed

188+分 已查看5 5,432+

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

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

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

我试图了解Angular(有时称为Angular2 +),然后遇到了@Module

  1. Imports进口货
  2. Declarations声明书
  3. Providers提供者

Following Angularjs-2 quick start

遵循Angularjs-2快速入门

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

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

Angular Concepts

角度概念

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

    imports使其他模块的导出声明在当前模块中可用

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

    declarations将使当前模块中的指令(包括组件和管道)可用于当前模块中的其他指令。 指令,组件或管道的选择器只有在声明或导入时才与HTML匹配。

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

    providers者应使DI知道服务和价值。 它们被添加到根范围,并且被注入到其他具有它们依赖关系的服务或指令中。

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

providers一种特殊情况是延迟加载的模块,它们具有自己的子注入器。 providers延迟加载模块的仅提供给默认此延迟加载模块(未整个应用程序,因为它与其他模块)。

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

有关模块的更多详细信息,另请参见https://angular.io/docs/ts/latest/guide/ngmodule.html

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

    exports使模块中的组件,指令和管道可用,从而将该模块添加到importsexports还可以用于重新导出诸如CommonModule和FormsModule之类的模块,这通常是在共享模块中完成的。

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

    entryComponents注册用于脱机编译的组件,以便它们可以与ViewContainerRef.createComponent()一起使用。 路由器配置中使用的组件是隐式添加的。

TypeScript (ES2015) imports

TypeScript(ES2015)导入

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

import ... from 'foo/bar' ( 可能解析为index.ts )用于TypeScript导入。 每当在另一个打字稿文件中声明的打字稿文件中使用标识符时,都需要这些。

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

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

See also jDriven — TypeScript and ES6 import syntax

另请参见jDriven — TypeScript和ES6导入语法

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

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

SourceTop

来源 顶部

在Angular中,如何确定活动路线? (In Angular, how do you determine the active route?)

187+ points ? 100,870+ viewed

187+分 已查看1 00,870+

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

187+分 1 00,870+浏览过Michael Oryl 问,

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

注意: 这里有很多不同的答案,大多数答案一次或一次都有效。 事实是,随着Angular团队更改了路由器,有效的方法已经改变了很多次。 最终将成为 Angular路由器的Router 3.0版本打破了许多解决方案,但提供了一个非常简单的解决方案。 从RC.3开始,首选解决方案是使用[routerLinkActive] ,如本答案所示。

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

在Angular应用程序中(我撰写本文时为2.0.0-beta.0版本中的当前版本),如何确定当前活动的路由是什么?

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

我正在开发一个使用Bootstrap 4的应用程序,当在<router-outp ut>标签中显示其关联组件时,我需要一种方法来将导航链接/按钮标记为活动状态。

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

我意识到当单击其中一个按钮时,我可以自己维护状态,但是这不会涉及将多条路径放入同一条路线的情况(例如主导航菜单以及主组件中的本地菜单) )。

Any suggestions or links would be appreciated. Thanks.

任何建议或链接将不胜感激。 谢谢。

jessepinho answered, (229+ points)

jessepinho 回答,(超过229分)

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

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

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

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

或者,如果只需要一个类,则为简化的非数组格式:

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

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

有关更多信息,请参见文档文献不routerLinkActive指令 。 (我主要是通过反复试验弄清楚这一点。)

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

更新:现在可以在此处找到更好的关于routerLinkActive指令的文档。 (感谢@Victor Hugo Arango A.在下面的评论中。)

SourceTop

来源 顶部

Angular CLI SASS选项 (Angular CLI SASS options)

187+ points ? 106,289+ viewed

187+分 已查看1 06,289+

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

187+分 已查看1 06,289+则JDillon522 询问,

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

我是Angular的新手,我来自Ember社区。 尝试使用基于Ember-CLI的新Angular-CLI。

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

我需要知道在新的Angular项目中处理SASS的最佳方法。 我尝试使用ember-cli-sass库来查看它是否可以正常运行,因为Angular-CLI的许多核心组件都使用了Ember-CLI模块。

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

它没有用,但还是不确定我是否配置错误。

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

另外,在新的Angular项目中组织样式的最佳方法是什么? 最好将sass文件与组件放在同一文件夹中。

Mertcan Diken answered, (323+ points)

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

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

当您使用angular cli创建项目时,请尝试以下操作:

ng new My_New_Project --style=sass

This generating all your components with predifined sass files.

这将生成带有预定义sass文件的所有组件。

If you want scss syntax create your project with :

如果要使用scss语法,请使用以下命令创建项目:

ng new My_New_Project --style=scss

If you are changing your existing style in your project

如果您要更改项目中的现有样式

ng set defaults.styleExt scss

Cli handles the rest of it.

Cli处理其余的工作。

SourceTop

来源 顶部

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

186+ points ? 102,556+ viewed

186+ points ? 1 02,556+ viewed

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

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

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

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

Mark Rajcok answered, (345+ points)

Mark Rajcok answered, (345+ points)

Try one of these:

Try one of these:

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

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

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

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

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

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

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

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

SourceTop

Source Top

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

184+ points ? 181,472+ viewed

184+ points ? 1 81,472+ viewed

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

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

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

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

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

This is the code:

这是代码:

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

basarat answered, (50+ points)

basarat answered, (50+ points)

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

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

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

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

SourceTop

Source Top

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

181+ points ? 54,337+ viewed

181+ points ? 5 4,337+ viewed

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

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

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

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

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

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

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

Nishchit Dhanani answered, (145+ points)

Nishchit Dhanani answered, (145+ points)

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

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

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

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

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

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

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

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

Update on 16 Sep 2016:

Update on 16 Sep 2016:

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

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

SourceTop

Source Top

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

175+ points ? 203,064+ viewed

175+ points ? 2 03,064+ viewed

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

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

I am using Angular 2 (TypeScript).

I am using Angular 2 (TypeScript).

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

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

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

Mark Rajcok answered, (370+ points)

Mark Rajcok answered, (370+ points)

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

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

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

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

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

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

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

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

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

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

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

SourceTop

Source Top

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

172+ points ? 48,252+ viewed

172+ points ? 4 8,252+ viewed

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

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

What am I doing wrong?

我究竟做错了什么?

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

The error is

The error is

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

Mark Rajcok answered, (403+ points)

Mark Rajcok answered, (403+ points)

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

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

I typed in instead of of in the ngFor expression.

I typed in instead of of in the ngFor expression.

Befor 2-beta.17, it should be:

Befor 2-beta.17 , it should be:

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

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

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

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

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

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

If we use in instead, it turns into

If we use in instead, it turns into

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

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

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

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

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

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

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

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

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

If we use in instead, it turns into

If we use in instead, it turns into

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

SourceTop

Source Top

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

171+ points ? 85,728+ viewed

171+ points ? 8 5,728+ viewed

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

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

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

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

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

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

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

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

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

Example at this plnkr.

Example at this plnkr .

Note the console error:

Note the console error:

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

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

Am I doing something wrong or is this a bug?

Am I doing something wrong or is this a bug?

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

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

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

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

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

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

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

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

SourceTop

Source Top

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

169+ points ? 95,029+ viewed

169+ points ? 9 5,029+ viewed

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

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

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

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

Mark Rajcok answered, (226+ points)

Mark Rajcok answered, (226+ points)

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

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

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

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

Here’s my understanding of how change detection works:

Here's my understanding of how change detection works:

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

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

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

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

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

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

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

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

  • Lifecycle hooks are called as part of change detection.

    Lifecycle hooks are called as part of change detection.

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

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

    ngOnChanges() to be notified of changes.

    ngOnChanges() to be notified of changes.

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

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

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

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

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

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

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

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

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

Other references to learn more:

Other references to learn more:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SourceTop

Source Top

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

167+ points ? 104,431+ viewed

167+ points ? 1 04,431+ viewed

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

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

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

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

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

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

import * as _ from 'lodash';

Results in:

Results in:

error TS2307: Cannot find module 'lodash'.

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

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

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

Results in:

Results in:

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

Both the gulp task and webstorm report the same issue.

Both the gulp task and webstorm report the same issue.

Funny fact, this returns no error:

Funny fact, this returns no error:

import 'lodash-es/lodash';

… but of course there is no “_” …

… but of course there is no “_” …

My tsconfig.json file:

My tsconfig.json file:

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

My gulpfile.js:

My gulpfile.js:

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

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

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

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

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

Taytay answered, (293+ points)

Taytay answered, (293+ points)

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

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

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

Then, in your .ts file:

Then, in your .ts file:

Either:

Either:

import * as _ from "lodash";

Or (as suggested by @Naitik):

Or (as suggested by @Naitik):

import _ from "lodash";

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

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

Edit on Feb 27th, 2017:

Edit on Feb 27th, 2017:

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

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

SourceTop

Source Top

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

160+ points ? 108,593+ viewed

160+ points ? 1 08,593+ viewed

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

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

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

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

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

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

Ludohen answered, (223+ points)

Ludohen answered, (223+ points)

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

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

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

Edit (since rc.1)

Edit (since rc.1)

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

Edit 2 (since 2.0.0)

Edit 2 (since 2.0.0)

see also : Router.events doc

see also : Router.events doc

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

SourceTop

Source Top

Global Events in Angular (Global Events in Angular)

157+ points ? 83,980+ viewed

157+ points ? 8 3,980+ viewed

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

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

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

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

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

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

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

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

pixelbits answered, (304+ points)

pixelbits answered, (304+ points)

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

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

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

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

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

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

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

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

To answer your questions:

To answer your questions:

What if I need to communicate between sibling components?

What if I need to communicate between sibling components?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Reference: Change Detection in Angular

Reference: Change Detection in Angular

SourceTop

Source Top

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

155+ points ? 60,183+ viewed

155+ points ? 6 0,183+ viewed

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

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

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

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

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

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

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

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

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

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

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

Thierry Templier answered, (97+ points)

Thierry Templier answered, (97+ points)

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

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

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

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

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

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

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

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

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

When using TypeScript, and configuring the compiler to the commonjs module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:

When using TypeScript, and configuring the compiler to the commonjs module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:

{"compilerOptions": {"target": "es5","module": "commonjs", // <------"moduleResolution": "node","sourceMap": true,"emitDecoratorMetadata": true,"experimentalDecorators": true,"removeComments": false,"noImplicitAny": false}
}

Webpack is a flexible module bundler. This means that it goes further and doesn’t only handle modules but also provides a way to package your application (concat files, uglify files, …). It also provides a dev server with load reload for development

Webpack is a flexible module bundler. This means that it goes further and doesn't only handle modules but also provides a way to package your application (concat files, uglify files, …). It also provides a dev server with load reload for development

SystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.

SystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.

SourceTop

Source Top

Angular: Can't find Promise, Map, Set and Iterator (Angular: Can’t find Promise, Map, Set and Iterator)

154+ points ? 90,201+ viewed

154+ points ? 9 0,201+ viewed

154+ points ? 90,201+ viewed Stav Alfi asked,

154+ points ? 9 0,201+ viewed Stav Alfi asked,

After installing Angular, the Typescript compiler keep getting some errors about not finding Promise, Map, Set and Iterator.

After installing Angular, the Typescript compiler keep getting some errors about not finding Promise , Map , Set and Iterator .

Until now I ignored them but now I need Promise so my code can work.

Until now I ignored them but now I need Promise so my code can work.

import {Component} from 'angular2/core';
@Component({selector: 'greeting-cmp',template: `<div>{{ asyncGreeting | async}}</div>`
})
export class GreetingCmp {asyncGreeting: Promise<string> = new Promise(resolve => {
// after 1 second, the promise will resolvewindow.setTimeout(() => resolve('hello'), 1000);});
}Additional information:
npm -v is 2.14.12
node -v is v4.3.1
typescript v is 1.6

The errors:

The errors:

................ERROS OF MY CODE.................C:\Users\armyTik\Desktop\angular2\greeting_cmp.tsError:(7, 20) TS2304: Cannot find name 'Promise'.Error:(7, 42) TS2304: Cannot find name 'Promise'..........................................C:\Users\armyTik\Desktop\angular2\node_modules\angular2\platform\browser.d.tsError:(77, 90) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\application_ref.d.tsError:(83, 60) TS2304: Cannot find name 'Promise'.Error:(83, 146) TS2304: Cannot find name 'Promise'.Error:(96, 51) TS2304: Cannot find name 'Promise'.Error:(96, 147) TS2304: Cannot find name 'Promise'.Error:(133, 90) TS2304: Cannot find name 'Promise'.Error:(171, 81) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\change_detection\parser\locals.d.tsError:(3, 14) TS2304: Cannot find name 'Map'.Error:(4, 42) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\debug\debug_node.d.tsError:(14, 13) TS2304: Cannot find name 'Map'.Error:(24, 17) TS2304: Cannot find name 'Map'.Error:(25, 17) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\di\provider.d.tsError:(436, 103) TS2304: Cannot find name 'Map'.Error:(436, 135) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\compiler.d.tsError:(12, 50) TS2304: Cannot find name 'Promise'.Error:(16, 41) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\linker\dynamic_component_loader.d.tsError:(108, 136) TS2304: Cannot find name 'Promise'.Error:(156, 150) TS2304: Cannot find name 'Promise'.Error:(197, 128) TS2304: Cannot find name 'Promise'.Error:(203, 127) TS2304: Cannot find name 'Promise'.Error:(204, 141) TS2304: Cannot find name 'Promise'.Error:(205, 119) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\core\render\api.d.tsError:(13, 13) TS2304: Cannot find name 'Map'.Error:(14, 84) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\async.d.tsError:(27, 33) TS2304: Cannot find name 'Promise'.Error:(28, 45) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\collection.d.tsError:(1, 25) TS2304: Cannot find name 'MapConstructor'.Error:(2, 25) TS2304: Cannot find name 'SetConstructor'.Error:(4, 27) TS2304: Cannot find name 'Map'.Error:(4, 39) TS2304: Cannot find name 'Map'.Error:(7, 9) TS2304: Cannot find name 'Map'.Error:(8, 30) TS2304: Cannot find name 'Map'.Error:(11, 43) TS2304: Cannot find name 'Map'.Error:(12, 27) TS2304: Cannot find name 'Map'.Error:(14, 23) TS2304: Cannot find name 'Map'.Error:(15, 25) TS2304: Cannot find name 'Map'.Error:(95, 41) TS2304: Cannot find name 'Set'.Error:(96, 22) TS2304: Cannot find name 'Set'.Error:(97, 25) TS2304: Cannot find name 'Set'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\lang.d.tsError:(13, 17) TS2304: Cannot find name 'Map'.Error:(14, 17) TS2304: Cannot find name 'Set'.Error:(78, 59) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\facade\promise.d.tsError:(2, 14) TS2304: Cannot find name 'Promise'.Error:(7, 32) TS2304: Cannot find name 'Promise'.Error:(8, 38) TS2304: Cannot find name 'Promise'.Error:(9, 35) TS2304: Cannot find name 'Promise'.Error:(9, 93) TS2304: Cannot find name 'Promise'.Error:(10, 34) TS2304: Cannot find name 'Promise'.Error:(11, 32) TS2304: Cannot find name 'Promise'.Error:(11, 149) TS2304: Cannot find name 'Promise'.Error:(12, 43) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\headers.d.tsError:(43, 59) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\http\url_search_params.d.tsError:(11, 16) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\browser\browser_adapter.d.tsError:(75, 33) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\angular2\src\platform\dom\dom_adapter.d.tsError:(85, 42) TS2304: Cannot find name 'Map'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\CoreOperators.d.tsError:(35, 67) TS2304: Cannot find name 'Promise'.Error:(50, 66) TS2304: Cannot find name 'Promise'.Error:(89, 67) TS2304: Cannot find name 'Promise'.Error:(94, 38) TS2304: Cannot find name 'Promise'.Error:(94, 50) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\Observable.d.tsError:(46, 62) TS2304: Cannot find name 'Promise'.Error:(47, 42) TS2304: Cannot find name 'Iterator'.Error:(103, 74) TS2304: Cannot find name 'Promise'.Error:(103, 84) TS2304: Cannot find name 'Promise'.Error:(143, 66) TS2304: Cannot find name 'Promise'.Error:(158, 65) TS2304: Cannot find name 'Promise'.Error:(201, 66) TS2304: Cannot find name 'Promise'.Error:(206, 38) TS2304: Cannot find name 'Promise'.Error:(206, 50) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\ForkJoinObservable.d.tsError:(6, 50) TS2304: Cannot find name 'Promise'.Error:(7, 58) TS2304: Cannot find name 'Promise'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\FromObservable.d.tsError:(7, 38) TS2304: Cannot find name 'Promise'.Error:(7, 51) TS2304: Cannot find name 'Iterator'.C:\Users\armyTik\Desktop\angular2\node_modules\rxjs\observable\PromiseObservable.d.tsError:(9, 31) TS2304: Cannot find name 'Promise'.Error:(10, 26) TS2304: Cannot find name 'Promise'.

Kris Hollenbeck answered, (162+ points)

Kris Hollenbeck answered, (162+ points)

Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0 (Angular RC4 — Angular ^2.0.0 with Typescript 2.0.0)

Updated 9/19/2016

Updated 9/19/2016

To get this to work with typescript 2.0.0, I did the following.

To get this to work with typescript 2.0.0, I did the following.

npm install --save-dev @types/core-js

npm install --save-dev @types/core-js

tsconfig.json

tsconfig.json

"compilerOptions": {"declaration": false,"emitDecoratorMetadata": true,"experimentalDecorators": true,"mapRoot": "./","module": "es6","moduleResolution": "node","noEmitOnError": true,"noImplicitAny": false,"outDir": "../dist/out-tsc","sourceMap": true,"target": "es5","typeRoots": ["../node_modules/@types"],"types": ["core-js"]}

More about @types with typescript 2.0.0.

More about @types with typescript 2.0.0.

  1. https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

    https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

  2. https://www.npmjs.com/~types

    https://www.npmjs.com/~types

Install Example:

Install Example:

npm install --save-dev @types/core-js

Duplicate Identifier errors

Duplicate Identifier errors

This is most likely because duplicate ecmascript 6 typings are already being imported from somewhere else most likely an old es6-shim.

This is most likely because duplicate ecmascript 6 typings are already being imported from somewhere else most likely an old es6-shim.

Double check typings.d.ts make sure there are no references to es6. Remove any reference to es6 from your typings directory if you have one.

Double check typings.d.ts make sure there are no references to es6 . Remove any reference to es6 from your typings directory if you have one.

For Example:

For Example:

This will conflict with types:['core-js'] in typings.json.

This will conflict with types:['core-js'] in typings.json.

{"globalDependencies": {"core-js": "registry:dt/core-js#0.0.0+20160602141332" // es6-shim will also conflict}
}

Including core-js in the types array in tsconfig.json should be the only place it is imported from.

Including core-js in the types array in tsconfig.json should be the only place it is imported from.

Angular CLI 1.0.0-beta.30

Angular CLI 1.0.0-beta.30

If you are using the Angular-CLI, remove the lib array in typings.json. This seems to conflict with declaring core-js in types.

If you are using the Angular-CLI, remove the lib array in typings.json . This seems to conflict with declaring core-js in types.

"compilerOptions" : {...// removed "lib": ["es6", dom"],...
},
"types" : ["core-js"]

Webstorm/Intellij Users using the Angular CLI

Webstorm/Intellij Users using the Angular CLI

Make sure the built in typescript compiler is disabled. This will conflict with the CLI. To compile your typescript with the CLI you can setup a ng serve configuration.

Make sure the built in typescript compiler is disabled. This will conflict with the CLI. To compile your typescript with the CLI you can setup a ng serve configuration.

Tsconfig compilerOptions lib vs types

Tsconfig compilerOptions lib vs types

If you prefer not to install core js type definitions there are some es6 libraries that come included with typescript. Those are used via the lib: [] property in tsconfig.

If you prefer not to install core js type definitions there are some es6 libraries that come included with typescript. Those are used via the lib: [] property in tsconfig.

See here for example: https://www.typescriptlang.org/docs/handbook/compiler-options.html

See here for example: https://www.typescriptlang.org/docs/handbook/compiler-options.html

Note: If --lib is not specified a default library is injected. The default library injected is: ? For --target ES5: DOM,ES5,ScriptHost ? For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

Note: If --lib is not specified a default library is injected. The default library injected is: ? For --target ES5: DOM,ES5,ScriptHost ? For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

tl;dr

tl;dr

Short answer either "lib": [ "es6", "dom" ] or "types": ["core-js"] can be used to resolve can't find Promise,Map, Set and Iterator. Using both however will cause duplicate identifier errors.

Short answer either "lib": [ "es6", "dom" ] or "types": ["core-js"] can be used to resolve can't find Promise,Map, Set and Iterator . Using both however will cause duplicate identifier errors.

SourceTop

Source Top

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

154+ points ? 89,893+ viewed

154+ points ? 8 9,893+ viewed

154+ points ? 89,893+ viewed Jon Catmull asked,

154+ points ? 8 9,893+ viewed Jon Catmull asked,

I have a parent component (CategoryComponent), a child component (videoListComponent) and an ApiService.

I have a parent component ( CategoryComponent ), a child component ( videoListComponent ) and an ApiService.

I have most of this working fine i.e. each component can access the json api and get its relevant data via observables.

I have most of this working fine ie each component can access the json api and get its relevant data via observables.

Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via @Input().

Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via @Input() .

CategoryComponent.html

CategoryComponent.html

<video-list *ngIf="category" [categoryId]="category.id"></video-list>

This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via @Input() but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).

This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via @Input() but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).

In AngularJS I would have done a $watch on the variable. What is the best way to handle this?

In AngularJS I would have done a $watch on the variable. What is the best way to handle this?

Alan C. S. answered, (181+ points)

Alan CS answered, (181+ points)

Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :

Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :

  1. You can use the ngOnChanges() lifecycle method as also mentioned in older answers:

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers:

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers: @Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }

    You can use the ngOnChanges() lifecycle method as also mentioned in older answers: @Input() categoryId: string; ngOnChanges(changes: SimpleChanges) { this.doSomething(changes.categoryId.currentValue); // You can also use categoryId.previousValue and // categoryId.firstChange for comparing old and new values }

  2. Documentation Links: ngOnChanges, SimpleChanges, SimpleChange

    Documentation Links: ngOnChanges, SimpleChanges, SimpleChange

    Demo Example: Look at

    Demo Example: Look at

    this plunker

    this plunker

  3. Alternately, you can also use an input property setter as follows:

    Alternately, you can also use an input property setter as follows:

    Alternately, you can also use an input property setter as follows:private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }

    Alternately, you can also use an input property setter as follows: private _categoryId: string; @Input() set categoryId(value: string) { this._categoryId = value; this.doSomething(this._categoryId); } get categoryId(): string { return this._categoryId; }

  4. Documentation Link: Look here.

    Documentation Link: Look here .

  5. Demo Example: Look at this plunker.

    Demo Example: Look at this plunker .

WHICH APPROACH SHOULD YOU USE?

WHICH APPROACH SHOULD YOU USE?

If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.

If your component has several inputs, then, if you use ngOnChanges(), you will get all changes for all the inputs at once within ngOnChanges(). Using this approach, you can also compare current and previous values of the input that has changed and take actions accordingly.

However, if you want to do something when only a particular single input changes (and you don’t care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).

However, if you want to do something when only a particular single input changes (and you don't care about the other inputs), then it might be simpler to use an input property setter. However, this approach does not provide a built in way to compare previous and current values of the changed input (which you can do easily with the ngOnChanges lifecycle method).

EDIT 2017–07–25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES

EDIT 2017–07–25: ANGULAR CHANGE DETECTION MAY STILL NOT FIRE UNDER SOME CIRCUMSTANCES

Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, provided that the data is a JS primitive datatype(string, number, boolean). However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.

Normally, change detection for both setter and ngOnChanges will fire whenever the parent component changes the data it passes to the child, provided that the data is a JS primitive datatype(string, number, boolean) . However, in the following scenarios, it will not fire and you have to take extra actions in order to make it work.

  1. If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look here.

    If you are using a nested object or array (instead of a JS primitive data type) to pass data from Parent to Child, change detection (using either setter or ngchanges) might not fire, as also mentioned in the answer by user: muetzerich. For solutions look here .

  2. If you are mutating data outside of the angular context (i.e., externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to this.

    If you are mutating data outside of the angular context (ie, externally), then angular will not know of the changes. You may have to use ChangeDetectorRef or NgZone in your component for making angular aware of external changes and thereby triggering change detection. Refer to this .

SourceTop

Source Top

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

154+ points ? 157,619+ viewed

154+ points ? 1 57,619+ viewed

154+ points ? 157,619+ viewed Miguel Lattuada asked,

154+ points ? 1 57,619+ viewed Miguel Lattuada asked,

Hi guys I’m creating a HTTP request on Angular, but I do not know how to add URL arguments (query string) to it.

Hi guys I'm creating a HTTP request on Angular, but I do not know how to add URL arguments (query string) to it.

this.http.get(StaticSettings.BASE_URL).subscribe((response) => this.onGetForecastResult(response.json()),(error) => this.onGetForecastError(error.json()),() => this.onGetForecastComplete()
);

Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2

Now my StaticSettings.BASE_URL is something like a url with no query string like: http://atsomeplace.com/ but I want it to be http://atsomeplace.com/?var1=val1&var2=val2

Where var1, and var2 fit on my Http request object? I want to add them like an object.

Where var1, and var2 fit on my Http request object? I want to add them like an object.

{query: {var1: val1,var2: val2}
}

and then just the Http module do the job to parse it into URL query string.

and then just the Http module do the job to parse it into URL query string.

toskv answered, (216+ points)

toskv answered, (216+ points)

The HttpClient methods allow you to set the params in it’s options.

The HttpClient methods allow you to set the params in it's options.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

You can configure it by importing the HttpClientModule from the @angular/common/http package.

import {HttpClientModule} from '@angular/common/http';@NgModule({imports: [ BrowserModule, HttpClientModule ],declarations: [ App ],bootstrap: [ App ]
})
export class AppModule {}

After that you can inject the HttpClient and use it to do the request.

After that you can inject the HttpClient and use it to do the request.

import {HttpClient} from '@angular/common/http'
import {HttpClient} from '@angular/common/http'@Component({selector: 'my-app',template: `<div><h2>Hello {{name}}</h2></div>`,
})
export class App {name:string;constructor(private httpClient: HttpClient) {this.httpClient.get('/url', {params: {appid: 'id1234',cnt: '5'},observe: 'response'}).toPromise().then(response => {console.log(response);}).catch(console.log);}
}

You can find a working example here.

You can find a working example here .

For angular versions prior to version 4 you can do the same using the Http service.

For angular versions prior to version 4 you can do the same using the Http service.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The Http.get method takes an object that implements RequestOptionsArgs as a second parameter.

The search field of that object can be used to set a string or a URLSearchParams object.

The search field of that object can be used to set a string or a URLSearchParams object.

An example:

一个例子:

// Parameters obj-let params: URLSearchParams = new URLSearchParams();params.set('appid', StaticSettings.API_KEY);params.set('cnt', days.toString());//Http request-return this.http.get(StaticSettings.BASE_URL, {search: params}).subscribe((response) => this.onGetForecastResult(response.json()), (error) => this.onGetForecastError(error.json()), () => this.onGetForecastComplete());

The documentation for the Http class has more details. It can be found here and an working example here.

The documentation for the Http class has more details. It can be found here and an working example here .

SourceTop

Source Top

How do you deploy Angular apps? (How do you deploy Angular apps?)

153+ points ? 89,991+ viewed

153+ points ? 8 9,991+ viewed

153+ points ? 89,991+ viewed Joseph Assem Sobhy asked,

153+ points ? 8 9,991+ viewed Joseph Assem Sobhy asked,

How do you deploy Angular apps once they reach the production phase?

How do you deploy Angular apps once they reach the production phase?

All the guides I’ve seen so far (even on angular.io) are counting on a lite-server for serving and browserSync to reflect changes — but when you finish with development, how can you publish the app?

All the guides I've seen so far (even on angular.io ) are counting on a lite-server for serving and browserSync to reflect changes — but when you finish with development, how can you publish the app?

Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?

Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?

Amid answered, (74+ points)

Amid answered, (74+ points)

You are actually here touching two questions in one. First one is how to host your application. And as @toskv mentioned its really too broad question to be answered and depends on numerous different things. Second one is more specific — how do you prepare the deployment version of the application. You have several options here:

You are actually here touching two questions in one. First one is how to host your application. And as @toskv mentioned its really too broad question to be answered and depends on numerous different things. Second one is more specific — how do you prepare the deployment version of the application. You have several options here:

  1. Deploy as it is. Just that — no minification, concatenation, name mangling etc. Transpile all your ts project, copy all your resulting js/css/… sources + dependencies to the hosting server and your are good to go.Deploy as it is. Just that — no minification, concatenation, name mangling etc. Transpile all your ts project, copy all your resulting js/css/… sources + dependencies to the hosting server and your are good to go.
  2. Deploy using special bundling tools. Like webpack or systemjs builder. They come with all possibilities that are lacking in #1. You can pack all your app code into just couple of js/css/… files that you reference in your html. Systemjs buider even allows you to get rid of need to include systemjs as part of your deployment package.Deploy using special bundling tools. Like webpack or systemjs builder. They come with all possibilities that are lacking in #1. You can pack all your app code into just couple of js/css/… files that you reference in your html. Systemjs buider even allows you to get rid of need to include systemjs as part of your deployment package.

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your html page. You do not have to reference all your compiled js files from the page though — systemjs as a module loader will take care of that.

Yes you will most likely need to deploy systemjs and bunch of other external libraries as part of your package. And yes you will be able to bundle them into just couple of js files you reference from your html page. You do not have to reference all your compiled js files from the page though — systemjs as a module loader will take care of that.

I know it sounds muddy — to help get you started with the #2 here are two really good sample applications:

I know it sounds muddy — to help get you started with the #2 here are two really good sample applications:

SystemJS builder: angular2 seed

SystemJS builder: angular2 seed

WebPack: angular2 webpack starter

WebPack: angular2 webpack starter

Look how they do it — and hopefully this will help you to find your way of bundling apps you make.

Look how they do it — and hopefully this will help you to find your way of bundling apps you make.

SourceTop

Source Top

ngFor with index as value in attribute (ngFor with index as value in attribute)

149+ points ? 195,294+ viewed

149+ points ? 1 95,294+ viewed

149+ points ? 195,294+ viewed Vivendi asked,

149+ points ? 1 95,294+ viewed Vivendi asked,

I have a simple ngFor loop which also keeps track of the current index. I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I have a simple ngFor loop which also keeps track of the current index . I want to store that index value in an attribute so I can print it. But I can't figure out how this works.

I basically have this:

I basically have this:

<ul *ngFor="#item of items; #i = index" data-index="#i"><li>{{item}}</li>
</ul>

I want to store the value of #i in the attribute data-index. I tried several methods but none of them worked.

I want to store the value of #i in the attribute data-index . I tried several methods but none of them worked.

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

I have a demo here: http://plnkr.co/edit/EXpOKAEIFlI9QwuRcZqp?p=preview

How can I store the index value in the data-index attribute?

How can I store the index value in the data-index attribute?

Thierry Templier answered, (284+ points)

Thierry Templier answered, (284+ points)

I would use this syntax to set the index value into an attribute of the HTML element:

I would use this syntax to set the index value into an attribute of the HTML element:

<ul><li *ngFor="#item of items; #i = index" [attr.data-index]="i">{{item}}</li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview .

Update for recent angular 2 releases You have to use let to declare the value rather than #.

Update for recent angular 2 releases You have to use let to declare the value rather than # .

<ul><li *ngFor="let item of items; let i = index" [attr.data-index]="i">{{item}}</li>
</ul>

SourceTop

Source Top

Define global constants in Angular 2 (Define global constants in Angular 2)

149+ points ? 128,101+ viewed

149+ points ? 1 28,101+ viewed

149+ points ? 128,101+ viewed AndreFeijo asked,

149+ points ? 1 28,101+ viewed AndreFeijo asked,

In Angular 1.x you can define constants like this:

In Angular 1.x you can define constants like this:

angular.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/')

What would be the equivalent in Angular2 (with Typescript)? I just don’t want to repeat the API base url over and over again in all my services.

What would be the equivalent in Angular2 (with Typescript)? I just don't want to repeat the API base url over and over again in all my services.

AndreFeijo answered, (159+ points)

AndreFeijo answered, (159+ points)

Below changes works for me on Angular 2 final version:

Below changes works for me on Angular 2 final version:

export class AppSettings {public static API_ENDPOINT='http://127.0.0.1:6666/api/';
}

And then in the service:

And then in the service:

import {Http} from 'angular2/http';
import {Message} from '../models/message';
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';
import {AppSettings} from '../appSettings';
import 'rxjs/add/operator/map';@Injectable()
export class MessageService {constructor(private http: Http) { }getMessages(): Observable<Message[]> {return this.http.get(AppSettings.API_ENDPOINT+'/messages').map(response => response.json()).map((messages: Object[]) => {return messages.map(message => this.parseData(message));});}private parseData(data): Message {return new Message(data);}
}

SourceTop

Source Top

Angular — Use pipes in services and components (Angular — Use pipes in services and components)

148+ points ? 75,716+ viewed

148+ points ? 7 5,716+ viewed

148+ points ? 75,716+ viewed POSIX-compliant asked,

148+ points ? 7 5,716+ viewed POSIX-compliant asked,

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

$filter('date')(myDate, 'yyyy-MM-dd');

Is it possible to use pipes in services/components like this in Angular?

Is it possible to use pipes in services/components like this in Angular?

cexbrayat answered, (271+ points)

cexbrayat answered, (271+ points)

As usual in Angular, you can rely on dependency injection:

As usual in Angular, you can rely on dependency injection:

import { DatePipe } from '@angular/common';
class MyService {constructor(private datePipe: DatePipe) {}transformDate(date) {this.datePipe.transform(myDate, 'yyyy-MM-dd');}
}

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe:

Add DatePipe to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe :

providers: [DatePipe,...]

Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).

Be warned though that the DatePipe was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table ).

If you’re using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

If you're using older Angular versions, you should add the Intl polyfill to your project to avoid any problem. See this related question for a more detailed answer.

SourceTop

Source Top

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.html

With the files being populated as follows:

With the files being populated as follows:

index.html

index.html

<html><head><base href="/"><title>Angular 2 QuickStart</title><link href="../css/bootstrap.css" rel="stylesheet"><!-- 1. Load libraries --><script src="node_modules/angular2/bundles/angular2-polyfills.js"></script><script src="node_modules/systemjs/dist/system.src.js"></script><script src="node_modules/rxjs/bundles/Rx.js"></script><script src="node_modules/angular2/bundles/angular2.dev.js"></script><script src="node_modules/angular2/bundles/router.dev.js"></script><!-- 2. Configure SystemJS --><script>System.config({packages: {        app: {format: 'register',defaultExtension: 'js'}}});System.import('app/boot').then(null, console.error.bind(console));</script></head><!-- 3. Display the application --><body><my-app>Loading...</my-app></body></html>

boot.ts

boot.ts

import {bootstrap}    from 'angular2/platform/browser'
import {ROUTER_PROVIDERS} from 'angular2/router';import {AppComponent} from './app.component'bootstrap(AppComponent, [ROUTER_PROVIDERS
]);

app.component.ts

app.component.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';import {RoutingTestComponent} from './routing-test.component';@Component({selector: 'my-app',template: `<h1>Component Router</h1><a [routerLink]="['RoutingTest']">Routing Test</a><router-outlet></router-outlet>`
})@RouteConfig([{path:'/routing-test', name: 'RoutingTest', component: RoutingTestComponent, useAsDefault: true},
])export class AppComponent { }

routing-test.component.ts

routing-test.component.ts

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';@Component({template: `<h2>Routing Test</h2><p>Interesting stuff goes here!</p>`
})
export class RoutingTestComponent { }

Attempting to run this code produces the error:

Attempting to run this code produces the error:

EXCEPTION: Template parse errors:
Can't bind to 'routerLink' since it isn't a known native property ("<h1>Component Router</h1><a [ERROR ->][routerLink]="['RoutingTest']">Routing Test</a><router-outlet></router-outlet>"): AppComponent@2:11

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0. However, the “working example” in one of the answers is based on pre-beta code — which may well still work, but I would like to know why the code I have created is not working.

I found a vaguely related issue here; router-link directives broken after upgrading to angular2.0.0-beta.0 . However, the “working example” in one of the answers is based on pre-beta code — which may well still work, but I would like to know why the code I have created is not working.

Any pointers would be gratefully received!

Any pointers would be gratefully received!

Günter Zöchbauer answered, (220+ points)

Günter Zöchbauer answered, (220+ points)

>=RC.5

>=R C.5

import the RouterModule See also https://angular.io/docs/ts/latest/guide/router.html

import the RouterModule See also https://angular.io/docs/ts/latest/guide/router.html

@NgModule({ imports: [RouterModule],...
})

>=RC.2

>=R C.2

app.routes.ts

app.routes.ts

import { provideRouter, RouterConfig } from '@angular/router';export const routes: RouterConfig = [...
];export const APP_ROUTER_PROVIDERS = [provideRouter(routes)];

main.ts

main.ts

import { bootstrap } from '@angular/platform-browser-dynamic';
import { APP_ROUTER_PROVIDERS } from './app.routes';bootstrap(AppComponent, [APP_ROUTER_PROVIDERS]);

<=RC.1

<=RC.1

Your code is missing

Your code is missing

@Component({...directives: [ROUTER_DIRECTIVES],...)}

You can’t use directives like routerLink or router-outlet without making them known to your component.

You can't use directives like routerLink or router-outlet without making them known to your component.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outlet> to be compatible with the web-components spec which require a - in the name of custom elements.

While directive names were changed to be case-sensitive in Angular2, elements still use - in the name like <router-outl et> to be compatible with the web-components spec which requ i re a - in the name of custom elements.

register globally

register globally

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...):

To make ROUTER_DIRECTIVES globally available, add this provider to bootstrap(...) :

provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi: true})

then it’s no longer necessary to add ROUTER_DIRECTIVES to each component.

then it's no longer necessary to add ROUTER_DIRECTIVES to each component.

SourceTop

Source Top

Angular 2 dynamic tabs with user-click chosen components (Angular 2 dynamic tabs with user-click chosen components)

143+ points ? 80,735+ viewed

143+ points ? 8 0,735+ viewed

143+ points ? 80,735+ viewed Cuel asked,

143+ points ? 8 0,735+ viewed Cuel asked,

I’m trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there’s plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.

I'm trying to setup a tab system that allows for components to register themselves (with a title). The first tab is like an inbox, there's plenty of actions/link items to choose from for the users, and each of these clicks should be able to instantiate a new component, on click. The actions / links comes in from JSON.

The instantiated component will then register itself as a new tab.

The instantiated component will then register itself as a new tab.

I’m not sure if this is the ‘best’ approach? Sofar the only guides I’ve seen are for static tabs, which doesn’t help.

I'm not sure if this is the 'best' approach? Sofar the only guides I've seen are for static tabs, which doesn't help.

So far I’ve only got the tabs service which is bootstrapped in main to persist throughout the app, looks ~something like this.

So far I've only got the tabs service which is bootstrapped in main to persist throughout the app, looks ~something like this.

export interface ITab { title: string; }@Injectable()
export class TabsService {private tabs = new Set<ITab>();addTab(title: string): ITab {let tab: ITab = { title };this.tabs.add(tab);return tab;}removeTab(tab: ITab) {this.tabs.delete(tab);}
}

Questions:

问题:

1) How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the DynamicComponentBuilder would be used?

1) How can I have a dynamic list in the inbox that creates new (different) tabs? I am sort of guessing the DynamicComponentBuilder would be used?

2) How can the components created from the inbox (on click) register themselves as tabs and also be shown? I’m guessing ng-content but I can’t find much info on how to use it

2) How can the components created from the inbox (on click) register themselves as tabs and also be shown? I'm guessing ng-content but I can't find much info on how to use it

Edit: Try to clarify

Edit: Try to clarify

Think of the inbox as a mail inbox, items are fetched as JSON and displays several items. Once one of the items is clicked, a new tab is created with that items action ‘type’. The type is then a component

Think of the inbox as a mail inbox, items are fetched as JSON and displays several items. Once one of the items is clicked, a new tab is created with that items action 'type'. The type is then a component

Edit2: Image

Edit2: Image

http://i.imgur.com/yzfMOXJ.png

http://i.imgur.com/yzfMOXJ.png

Günter Zöchbauer answered, (190+ points)

Günter Zöchbauer answered, (190+ points)

update

update

Angular 5 StackBlitz example

Angular 5 StackBlitz example

update

update

ngComponentOutlet was added to 4.0.0-beta.3

ngComponentOutlet was added to 4.0.0-beta.3

update

update

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

There is a NgComponentOutlet work in progress that does something similar https://github.com/angular/angular/pull/11235

RC.7

RC.7

Plunker example RC.7

Plunker example RC.7

// Helper component to add dynamic components
@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;@Input() type: Type<Component>;cmpRef: ComponentRef<Component>;private isViewInitialized:boolean = false;constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) {}updateComponent() {if(!this.isViewInitialized) {return;}if(this.cmpRef) {// when the `type` input changes we destroy a previously // created component before creating the new onethis.cmpRef.destroy();}let factory = this.componentFactoryResolver.resolveComponentFactory(this.type);this.cmpRef = this.target.createComponent(factory)// to access the created instance use// this.compRef.instance.someProperty = 'someValue';// this.compRef.instance.someOutput.subscribe(val => doSomething());}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Usage example

Usage example

// Use dcl-wrapper component
@Component({selector: 'my-tabs',template: `<h2>Tabs</h2><div *ngFor="let tab of tabs"><dcl-wrapper [type]="tab"></dcl-wrapper></div>
`
})
export class Tabs {@Input() tabs;
}@Component({selector: 'my-app',template: `<h2>Hello {{name}}</h2><my-tabs [tabs]="types"></my-tabs>
`
})
export class App {// The list of components to create tabs fromtypes = [C3, C1, C2, C3, C3, C1, C1];
}@NgModule({imports: [ BrowserModule ],declarations: [ App, DclWrapper, Tabs, C1, C2, C3],entryComponents: [C1, C2, C3],bootstrap: [ App ]
})
export class AppModule {}

See also angular.io DYNAMIC COMPONENT LOADER

See also angular.io DYNAMIC COMPONENT LOADER

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

older versions xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

This changed again in Angular2 RC.5

This changed again in Angular2 RC.5

I will update the example below but it’s the last day before vacation.

I will update the example below but it's the last day before vacation.

This Plunker example demonstrates how to dynamically create components in RC.5

This Plunker example demonstrates how to dynamically create components in RC.5

Update — use ViewContainerRef.createComponent()

Update — use ViewContainerRef .createComponent()

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

Because DynamicComponentLoader is deprecated, the approach needs to be update again.

@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target;@Input() type;cmpRef:ComponentRef;private isViewInitialized:boolean = false;constructor(private resolver: ComponentResolver) {}updateComponent() {if(!this.isViewInitialized) {return;}if(this.cmpRef) {this.cmpRef.destroy();}this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {this.cmpRef = this.target.createComponent(factory)// to access the created instance use// this.compRef.instance.someProperty = 'someValue';// this.compRef.instance.someOutput.subscribe(val => doSomething());});}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Plunker example RC.4Plunker example beta.17

Plunker example RC.4 Plunker example beta.17

Update — use loadNextToLocation

Update — use loadNextToLocation

export class DclWrapper {@ViewChild('target', {read: ViewContainerRef}) target;@Input() type;cmpRef:ComponentRef;private isViewInitialized:boolean = false;constructor(private dcl:DynamicComponentLoader) {}updateComponent() {// should be executed every time `type` changes but not before `ngAfterViewInit()` was called // to have `target` initializedif(!this.isViewInitialized) {return;}if(this.cmpRef) {this.cmpRef.destroy();}this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {this.cmpRef = cmpRef;});}ngOnChanges() {this.updateComponent();}ngAfterViewInit() {this.isViewInitialized = true;this.updateComponent();  }ngOnDestroy() {if(this.cmpRef) {this.cmpRef.destroy();}    }
}

Plunker example beta.17

Plunker example beta.17

original

original

Not entirely sure from your question what your requirements are but I think this should do what you want.

Not entirely sure from your question what your requirements are but I think this should do what you want.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

The Tabs component gets an array of types passed and it creates "tabs" for each item in the array.

@Component({selector: 'dcl-wrapper',template: `<div #target></div>`
})
export class DclWrapper {constructor(private elRef:ElementRef, private dcl:DynamicComponentLoader) {}@Input() type;ngOnChanges() {if(this.cmpRef) {this.cmpRef.dispose();}this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {this.cmpRef = cmpRef;});}
}@Component({selector: 'c1',template: `<h2>c1</h2>`})
export class C1 {
}@Component({selector: 'c2',template: `<h2>c2</h2>`
})
export class C2 {
}
@Component({selector: 'c3',template: `<h2>c3</h2>`})
export class C3 {
}@Component({selector: 'my-tabs',directives: [DclWrapper],template: `<h2>Tabs</h2><div *ngFor="let tab of tabs"><dcl-wrapper [type]="tab"></dcl-wrapper></div>
`
})
export class Tabs {@Input() tabs;
}@Component({selector: 'my-app',directives: [Tabs]template: `<h2>Hello {{name}}</h2><my-tabs [tabs]="types"></my-tabs>
`
})
export class App {types = [C3, C1, C2, C3, C3, C1, C1];
}

Plunker example beta.15 (not based on your Plunker)

Plunker example beta.15 (not based on your Plunker)

There is also a way to pass data along that can be passed to the dynamically created component like (someData would need to be passed like type)

There is also a way to pass data along that can be passed to the dynamically created component like ( someData would need to be passed like type )

this.dcl.loadIntoLocation(this.type, this.elRef, 'target').then((cmpRef) => {cmpRef.instance.someProperty = someData;this.cmpRef = cmpRef;
});

There is also some support to use dependency injection with shared services.

There is also some support to use dependency injection with shared services.

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

For more details see https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

SourceTop

Source Top

Delegation: EventEmitter or Observable in Angular (Delegation: EventEmitter or Observable in Angular)

141+ points ? 78,505+ viewed

141+ points ? 7 8,505+ viewed

141+ points ? 78,505+ viewed the_critic asked,

141+ points ? 7 8,505+ viewed the_critic asked,

I am trying to implement something like a delegation pattern in Angular. When the user clicks on a nav-item, I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.

I am trying to implement something like a delegation pattern in Angular. When the user clicks on a nav-item , I would like to call a function which then emits an event which should in turn be handled by some other component listening for the event.

Here is the scenario: I have a Navigation component:

Here is the scenario: I have a Navigation component:

import {Component, Output, EventEmitter} from 'angular2/core';@Component({// other properties left out for brevityevents : ['navchange'], template:`<div class="nav-item" (click)="selectedNavItem(1)"></div>`
})export class Navigation {@Output() navchange: EventEmitter<number> = new EventEmitter();selectedNavItem(item: number) {console.log('selected nav item ' + item);this.navchange.emit(item)}}

Here is the observing component:

Here is the observing component:

export class ObservingComponent {// How do I observe the event ? // <----------Observe/Register Event ?-------->public selectedNavItem(item: number) {console.log('item index changed!');}}

The key question is, how do I make the observing component observe the event in question ?

The key question is, how do I make the observing component observe the event in question ?

Mark Rajcok answered, (306+ points)

Mark Rajcok answered, (306+ points)

Update 2016–06–27: instead of using Observables, use either

Update 2016–06–27: instead of using Observables, use either

  • a BehaviorSubject, as recommended by @Abdulrahman in a comment, ora BehaviorSubject, as recommended by @Abdulrahman in a comment, or
  • a ReplaySubject, as recommended by @Jason Goemaat in a commenta 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 availableuse a CDN ? but we would rather serve these files to guarantee that they will be available
  • copy dependencies to dist/vendor after our ng build -prod ? But that seems like something angular-cli should provide since it 'takes care' of the build part ?

    copy dependencies to dist/vendor after our ng build -prod ? But that seems like something angular-cli should provide since it 'takes care' of the build part ?

  • adding jquery, bootstrap and tether in src/system-config.ts and somehow pull them into our bundle in main.ts ? But that seemed wrong considering that we are not going to explicitly use them in our application’s code (unlike moment.js or something like lodash, for example)adding jquery, bootstrap and tether in src/system-config.ts and somehow pull them into our bundle in main.ts ? But that seemed wrong considering that we are not going to explicitly use them in our application's code (unlike moment.js or something like lodash, for example)

pd farhad answered, (202+ points)

pd farhad answered, (202+ points)

**IMPORTANT UPDATE: ng2-bootstrap is now replaced by ngx-bootstrap **

**IMPORTANT UPDATE: ng2-bootstrap is now replaced by ngx-bootstrap **

ngx-bootstrap supports both angular 3 and 4.

ngx-bootstrap supports both angular 3 and 4.

Update : 1.0.0-beta.11-webpack or above versions

Update : 1.0.0-beta.11-webpack or above versions

First of all check your angular-cli version with the following command in the terminal: ng -v

First of all check your angular-cli version with the following command in the terminal: ng -v

If your angular-cli version is greater than 1.0.0-beta.11-webpack then you should follow these steps:

If your angular-cli version is greater than 1.0.0-beta.11-webpack then you should follow these steps:

  1. install ngx-bootstrap and bootstrap:

    install ngx-bootstrap and bootstrap:

    install ngx-bootstrap and bootstrap:npm install ngx-bootstrap bootstrap --save

    install ngx-bootstrap and bootstrap: npm install ngx-bootstrap bootstrap --save

This line installs bootstrap 3 nowadays, but can install bootstrap 4 in future. Keep in mind ngx-bootstrap supports both versions.

This line installs bootstrap 3 nowadays, but can install bootstrap 4 in future. Keep in mind ngx-bootstrap supports both versions.

  1. open src/app/app.module.ts and add

    open src/app/app.module.ts and add

    open src/app/app.module.ts and addimport { AlertModule } from 'ngx-bootstrap'; ... @NgModule({ ... imports: [AlertModule.forRoot(), ... ], ... })

    open src/app/app.module.ts and add import { AlertModule } from 'ngx-bootstrap'; ... @NgModule({ ... imports: [AlertModule.forRoot(), ... ], ... })

  2. open angular-cli.json and insert a new entry into the styles array

    open angular-cli.json and insert a new entry into the styles array

    open angular-cli.json and insert a new entry into the styles array"styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ],

    open angular-cli.json and insert a new entry into the styles array "styles": [ "styles.css", "../node_modules/bootstrap/dist/css/bootstrap.min.css" ],

  3. open src/app/app.component.html and add

    open src/app/app.component.html and add

    open src/app/app.component.html and add<alert type="success">hello&lt;/alert>

    open src/app/app.component.html and add <alert type="success">hello&l t;/alert>

1.0.0-beta.10 or below versions:

1.0.0-beta.10 or below versions:

And, if your angular-cli version is 1.0.0-beta.10 or below versions then you can use below steps.

And, if your angular-cli version is 1.0.0-beta.10 or below versions then you can use below steps.

First go to the project directory and type

First go to the project directory and type

npm install ngx-bootstrap --save

then open your angular-cli-build.js and add this line

then open your angular-cli-build.js and add this line

vendorNpmFiles: [..................'ngx-bootstrap/**/*.js',....................]

now open your src/system-config.ts, write

now open your src/system-config.ts , write

const map:any = {..................'ngx-bootstrap': 'vendor/ngx-bootstrap',....................
}

and

const packages: any = {'ngx-bootstrap': {format: 'cjs',defaultExtension: 'js',main: 'ngx-bootstrap.js'}
};

SourceTop

Source Top

access key and value of object using *ngFor (access key and value of object using *ngFor)

136+ points ? 139,816+ viewed

136+ points ? 1 39,816+ viewed

136+ points ? 139,816+ viewed Pardeep Jain asked,

136+ points ? 1 39,816+ viewed Pardeep Jain asked,

Bit confused about how to get Key and Value of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like

Bit confused about how to get Key and Value of object in angular2 while usng *ngFor for iteration over object. i know in angular 1.x there is syntax like

ng-repeat="(key, value) in demo"

but in angular2 i don’t know i tired the same but did’t get successful. i have tried the below code but did’t run please tell me where i am doing wrong.

but in angular2 i don't know i tired the same but did't get successful. i have tried the below code but did't run please tell me where i am doing wrong.

<ul><li *ngFor='#key of demo'>{{key}}</li>
</ul>demo = {'key1': [{'key11':'value11'}, {'key12':'value12'}],'key2': [{'key21':'value21'}, {'key22':'value22'}],}

here is plnkr where i have tried the same : http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

here is plnkr where i have tried the same : http://plnkr.co/edit/mIj619FncOpfdwrR0KeG?p=preview

I want to get key1 and key2 dynamically using *ngFor. How to get it? i searched a lot found idea of using pipe but how to use i dont know. is there any inbuild pipe for doing same in angular2 ?

I want to get key1 and key2 dynamically using *ngFor. How to get it? i searched a lot found idea of using pipe but how to use i dont know. is there any inbuild pipe for doing same in angular2 ?

Thierry Templier answered, (134+ points)

Thierry Templier answered, (134+ points)

You could create a custom pipe to return the list of key for each element. Something like that:

You could create a custom pipe to return the list of key for each element. Something like that:

import { PipeTransform, Pipe } from '@angular/core';@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {transform(value, args:string[]) : any {let keys = [];for (let key in value) {keys.push(key);}return keys;}
}

and use it like that:

and use it like that:

<tr *ngFor="let c of content">           <td *ngFor="let key of c | keys">{{key}}: {{c[key]}}</td>
</tr>

Edit

Edit

You could also return an entry containing both key and value:

You could also return an entry containing both key and value:

@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {transform(value, args:string[]) : any {let keys = [];for (let key in value) {keys.push({key: key, value: value[key]});}return keys;}
}

and use it like that:

and use it like that:

<span *ngFor="let entry of content | keys">           Key: {{entry.key}}, value: {{entry.value}}
</span>

SourceTop

Source Top

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

134+ points ? 63,054+ viewed

134+ points ? 6 3,054+ viewed

134+ points ? 63,054+ viewed Mark Rajcok asked,

134+ points ? 6 3,054+ viewed Mark Rajcok asked,

What am I doing wrong?

我究竟做错了什么?

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

The error is

The error is

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

Mark Rajcok answered, (325+ points)

Mark Rajcok answered, (325+ points)

I missed let in front of talk:

I missed let in front of talk :

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

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead. <div *ngFor="#talk of talks"> now becomes <div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead. <div *ngFor="#talk of talk s"> now be comes <div *ngFor="let talk o f talks">

Original answer:

Original answer:

I missed # in front of talk:

I missed # in front of talk :

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

It is so easy to forget that #. I wish the Angular exception error message would instead say:you forgot that # again.

It is so easy to forget that # . I wish the Angular exception error message would instead say: you forgot that # again .

SourceTop

Source Top

How to add font-awesome to Angular 2 + CLI project (How to add font-awesome to Angular 2 + CLI project)

132+ points ? 71,934+ viewed

132+ points ? 7 1,934+ viewed

132+ points ? 71,934+ viewed Nik asked,

132+ points ? 7 1,934+ viewed Nik asked,

I’m using Angular 2+ and Angular CLI.

I'm using Angular 2+ and Angular CLI.

How do I add font-awesome to my project?

How do I add font-awesome to my project?

AIon answered, (285+ points)

AIon answered, (285+ points)

After Angular 2.0 final release, the structure of the Angular2 CLI project has been changed — you don’t need any vendor files, no system.js — only webpack. So you do:

After Angular 2.0 final release, the structure of the Angular2 CLI project has been changed — you don't need any vendor files, no system.js — only webpack. So you do:

  1. npm install font-awesome --save

    npm install font-awesome --save

  2. In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below:

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below:

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below: “apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ] ]

    In the angular-cli.json file locate the styles[] array and add font-awesome references directory here, like below: “apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ] ]

  3. Place some font-awesome icons in any html file you want:

    Place some font-awesome icons in any html file you want:

    Place some font-awesome icons in any html file you want: <i class=”fa fa-american-sign-language-interpreting fa-5x” aria-hidden=”true”> </i>

    Place some font-awesome icons in any html file you want: <i class=”fa fa-american-sign-language-interpreting fa-5x” aria-hidden=”true”> </i>

  4. Run ng build and ng serve again - because the watchers are only for the src folder and angular-cli.json is not observed for changes.

    Run ng build and ng serve again - because the watchers are only for the src folder and angular-cli.json is not observed for changes.

  5. Enjoy your awesome icons!Enjoy your awesome icons!

SourceTop

Source Top

Difference between HTTP and HTTPClient in angular 4? (Difference between HTTP and HTTPClient in angular 4?)

130+ points ? 47,082+ viewed

130+ points ? 4 7,082+ viewed

130+ points ? 47,082+ viewed Aioub Amini asked,

130+ points ? 4 7,082+ viewed Aioub Amini asked,

I want to know which one to use to build a mock web service to test the Angular program?

I want to know which one to use to build a mock web service to test the Angular program?

AngularInDepth.com answered, (208+ points)

AngularInDepth.com answered, (208+ points)

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

Use the HttpClient class from HttpClientModule if you're using Angular 4.3.x and above:

import { HttpClientModule } from '@angular/common/http';@NgModule({imports: [BrowserModule,HttpClientModule],...class MyService() {constructor(http: HttpClient) {...}

It’s an upgraded version of http from @angular/http module with the following improvements:

It's an upgraded version of http from @angular/http module with the following improvements:

  • Interceptors allow middleware logic to be inserted into the pipelineInterceptors allow middleware logic to be inserted into the pipeline
  • Immutable request/response objectsImmutable request/response objects
  • Progress events for both request upload and response downloadProgress 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 typesTyped, synchronous response body access, including support for JSON body types
  • JSON is an assumed default and no longer needs to be explicitly parsedJSON is an assumed default and no longer needs to be explicitly parsed
  • Post-request verification & flush based testing frameworkPost-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面试题及答案

angular面试题及答案_关于最流行的Angular问题的StackOverflow上的48个答案相关推荐

  1. angular js创建表单_如何优雅的使用 Angular 表单验证

    随便说说,这一节可以跳过 去年参加 ngChine 2018 杭州开发者大会的时候记得有人问我: Worktile 是什么时候开始使用 Angular 的,我说是今年(2018年) 3 月份开始在新模 ...

  2. 工程经济作业1答案_大工19秋《工程经济学》在线作业1(参考答案)

    大工 19 秋<工程经济学>在线作业 1-0001 试卷总分 :100 得分 :100 一.单选题 ( 共 10 道试题 , 共 60 分 ) 1. 下列有关利润总额的表达式中,正确的是( ...

  3. angular图片传到后台_告诉你,SpringBoot+Angular有多牛逼!

    点击上方[全栈开发者社区]→右上角[...]→[设为星标⭐] 零 本文基于<SpringBoot+Angular入门实例教程>第5.1节的内容理解并简化而来.本文的目的浅析前后台分离的普通 ...

  4. 奥鹏教育微学吧JAVA答案_西交20秋《Java语言》在线作业【标准答案】

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 西交<Java语言>在线作业 试卷总分:100 得分:100 一.单选题 (共 30 道试题,共 60 分) 1.给出下面代码,关于该程序以下 ...

  5. 国开mysql答案_国开《3868MySQL数据库应用-0006》期末机考【答案】

    3868MySQL数据库应用-0006 单选题(共25题,共75分) 1. 下述()不是DBA数据库管理员的职责. A 完整性约束说明 B 定义数据库模式 C 数据库安全 D 数据库管理系统设计 参考 ...

  6. 数据采集技术python网络爬虫答案_高校邦网络数据采集与Python爬虫【带实验】章节答案...

    认识必然和争取自由,是人类认识世界和改造世界的根本目标. 答:正确 内源性凝血途径的始动因子是( ) 答:因子XII 对某一主题进行自定义修改之后,保存成何种格式,方便下次快速应用? 答:另存为&qu ...

  7. 大学python考试题及答案_中国大学慕课mooc用Python玩转数据期末考试大全答案

    在风险管理中,所有危险源的原因与后果是一一对应的. [单选题]在EOQ模型中, 当一次订货费增加 21%, 那最优订购量如何改变 [单选题]是客户想象中可能得到的服务. [多选题]仔细阅读下列材料后, ...

  8. 山东财经大学python实验六答案_金融学(山东财经大学)智慧树知道2020章节测验答案...

    调查是科学探究常用的方法之一.关于调查不正确的叙述是()A.人口普查是调查B.森林资源的清查是调查C.要对 想一想,在你家中是否存在着生物(如果有,注意一下它们的生活环境),设计并完成一份家庭生物调查 ...

  9. python第五周项目答案_工作页python流程控制(第五周 ).doc_学小易找答案

    [单选题]Mary is ()hardworking than her sister, but she failed in the exam. (5.0分) [单选题]设a.b为float型变量,则以 ...

最新文章

  1. linux常用命令(1)帮助命令man使用
  2. boost::mpi模块实现scan集合的测试
  3. iOS之深入解析CocoaPods的GitLab CI与组件自动化构建与发布
  4. SystemCenter2012SP1实践(23)私有云的权限设计
  5. zabbix源码安装
  6. (转)马云的江湖 PK 史玉柱的兵法
  7. IDEA启动:Internal error. Please refer to https://jb.gg/ide/critical-startup-errors
  8. POI导出之我的实践篇
  9. 找出一批正整数中的最大偶数_c语言上机题库
  10. Qt编写onvif搜索和云台控制工具源码
  11. EOS在ubuntu16.04搭建私有链(二)
  12. “科比男孩”被美国大学录取 即将出国圆梦
  13. WWDC2016临近 苹果开始布置会场外LOGO
  14. 联想 ThinkPad P53接耳机有声音而外放没声音
  15. 树莓派 配置USB麦克风声卡
  16. compareto返回1和-1的区别_温故篇:Comparable与Compatator的区别
  17. jenkins持续集成与持续交付
  18. android 美团多渠道打包方案
  19. Linux 查找命令(find、locate 、grep )
  20. 3D mark 05 测试

热门文章

  1. 如何保证消息队列的高可用?透彻分析源码
  2. 测开2 - Python(文件操作)
  3. 让内核突破512字节的限制
  4. Linux下查看txt文档
  5. struts2官方 中文教程 系列六:表单验证
  6. [deviceone开发]-do_Album的简单示例
  7. 怎么去掉Flex4生成的SWF加载时的进度条
  8. IIS6.0的web园--最大工作进程数
  9. visual studio 2005中生成网站和发布网站区别
  10. AtomicStampedReference源码分析