Angular2--Directives

来源:互联网 发布:用电脑修改游戏数据 编辑:程序博客网 时间:2024/04/29 20:41

Angular 模版(templates)是动态的. 当Angular 渲染模板时, 会根据directives里的说明来转化成DOM.

一个 directive 就是一个有 @Directive decorator 的class . 一个 component 是一个 directive + template; 一个 @Component decorator 实际上是一个有模板的 @Directive decorator。

While a component is technically a directive, components are so distinctive and central to Angular applications that this architectural overview separates components from directives.

从技术角度来讲,一个 component 就是 一个directive, components 在 Angular 应用中很重要,所以有必要将component和directive区分一下.

存在两种directives: 结构directives 和 属性directives.

通常directives会和属性一样出现在元素标签里,有时是通过name,但更多的是一个声明或绑定的target。

结构 directives 通过增、删、改DOM元素来改变布局。

<li *ngFor="let hero of heroes"></li><app-hero-detail *ngIf="selectedHero"></app-hero-detail>

*ngFor*ngIf 就是结构指令

属性 directives 改变一个已有元素的样式或行为。在模板中看起来很像普通的HTML 属性。

ngModel directive 声明来一个双向绑定,就是一个属性directive。 ngModel 编辑一个已有元素 (通常是一个 ) 的行为,通过设置它的属性和响应绑定事件。

<input [(ngModel)]="hero.name">

Angular 还有一些可以改变布局的指令 (例如, ngSwitch) 或者修改DOM 元素或者 components (例如, ngStyle and ngClass).

当然你也可以自己写directives 。

angular.io/guide

原创粉丝点击