指令可用于操作 DOM 元素。当您想要制作可供您团队或世界中的其他程序员使用的自定义(第三方)指令时,它非常有用。
基本上有三种类型的指令。
1) 结构指令
2) 属性指令
3) 组件指令(带模板)
1) 结构指令 通常操纵视图/模板的结构。例如。 *ngFor 将根据您的列表计数生成元素。 *ngIf 将根据传递的值显示/隐藏视图。
2) 属性指令 允许您在 DOM 元素上添加属性,然后您可以使用该 DOM 元素做很多事情。
例如。
<p myColor >Color me!</p> //<<< this helps you to grab DOM element using ElementRef and then I'll color it as shown below.
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[myColor]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'red';
}
}
这里 myColor 只是一个 attribute directive,因为它作为 attribute 添加到 DOM 元素中,但是这个 属性不接受任何值。
现在让我们为 myColor 属性添加一个值,
<p [myColor]="color">Highlight me!</p>
@Input :这里我们传递
color variable(Angular2 bindings) 所以在指令中我们必须有一个机制来接收它。所以我们应该使用
@Input API 因为我们要从父组件中获取价值(你可以将指令视为父组件的子组件)
@Output :如果您希望指令发出一些应该由父组件接收的值,那么您应该使用
@Output API