1、涉及装饰器
下面例子中主要用到了@HostBinding()和@HostListener()两个装饰器,具体作用通过运行下面例子就可以明白。
2、创建指令
// 以下命令会创建TestDirective指令并自动添加到AppModule
ng g directive directive/test
3、TestDirective代码
import { Directive, HostBinding, HostListener, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[appTest]'
})
export class TestDirective {
@HostBinding('title')
public title = 'This is a test title!';
@HostBinding('id')
public testId = '';
constructor(
private r2: Renderer2,
private ef: ElementRef
) { }
@HostListener('click')
public clickTest() {
this.testId = 'test-id';
this.r2.setAttribute(this.ef.nativeElement, 'id', this.testId);
}
// test为class选择器名称, .test {font-size: 30px;color #f00;}
&