Angular自定义指令
Angular自定义指令(一 ) 实现添加某个属性,标签颜色发生改变
1.创建自定义指令文件(选择器)
ng g directive directive/yustyle
2.ts文件中
import { Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[appYustyle]'
})
export class YustyleDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.color = 'pink';
}
}
3.在所需要的标签上加上颜色指令appYustyle
<h1 appYustyle>我是粉色字体</h1>
<h2>我没颜色</h2>
4.效果
Angular自定义指令(二) 实现传入自定义类名
1.创建自定义指令文件(选择器)
ng g directive directive/abc
2.ts文件中
import { Directive, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[appAbc]',
})
export class AbcDirective {
@Input() appAbc;
constructor(public el: ElementRef) {}
// tslint:disable-next-line: use-lifecycle-interface
ngOnChanges(): void {
this.el.nativeElement.className = this.appAbc;
}
}
3.在所需要的标签上加上颜色指令appAbc
<h2 [appAbc]="'yuyu'">我是h2</h2>
<h3>我是h3</h3>
4.效果 标签上会有yuyu类
Angular自定义指令(三) 实现点击变红
1.创建自定义指令文件(选择器)
ng g directive directive/abc
2.ts文件中
import { Directive, Input, ElementRef } from '@angular/core';
@Directive({
selector: '[appAbc]',
})
export class AbcDirective {
@Input() appAbc;
constructor(public el: ElementRef) {}
ngOnChanges(): void {
this.el.nativeElement.addEventListener('click', () => {
this.el.nativeElement.style.color = 'red';
});
}
}
3.在所需要的标签上加上颜色指令appAbc
<h2 [appAbc]="'yuyu'">我是h2</h2>
<h3>我是h3</h3>
4.效果 点击变红色