Angular中的指令是一个js类,它被声明为@directive。Angular中有3种指令表现形式。
组件的指令
它们构成了主类,包含了组件在运行时应该如何处理、实例化和使用的详细信息。
结构指示
结构指令主要处理操作dom元素。结构指令在指令前有符号。例如,ngIf和*ngFor。
属性指示
属性指令处理修改dom元素的外观和行为。您可以创建自己的指令。
怎么自定义自己的指令?
采用angular-cli命令创建
ng g directive nameofthedirective
e.g
ng g directive directives/bgColor
运行命令后生成如下文件:
CYGR-0101-01-0137deMacBook-Pro:jinadmin cygr-0101-01-0137$ ng g directive directives/bgColor
CREATE src/app/directives/bg-color.directive.spec.ts (229 bytes)
CREATE src/app/directives/bg-color.directive.ts (143 bytes)
UPDATE src/app/app.module.ts (2279 bytes)
app.module.ts文件导入及声明刚创建的指令
bg-color. directive
import { Directive } from '@angular/core';
@Directive({
selector: '[appBgColor]'
})
export class BgColorDirective {
constructor() { }
}
怎样使用指令?
我们要在要使用此类指令的页面模板中添加下面的代码示例
<div>
<span>hello world.</span>
</div>
<div>
<span appBgColor>hello world.</span>
</div>
指令处理
import { Directive , ElementRef} from '@angular/core';
@Directive({
selector: '[appBgColor]'
})
export class BgColorDirective {
constructor(Element: ElementRef) {
console.log(Element);
Element.nativeElement.style.backgroundColor = 'red';
Element.nativeElement.innerText="Color is changed by bgColor Directive. ";
}
}
然后,添加此指令的dom就变成指令处理后的结果
最后可以看下渲染后的结果