Angular自定义指令

Angular自定义指令

Angular自定义指令(一 ) 实现添加某个属性,标签颜色发生改变
1.创建自定义指令文件(选择器)
ng g directive directive/yustyle
Angular自定义指令_第1张图片
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

我是粉色字体

我没颜色

4.效果
Angular自定义指令_第2张图片

Angular自定义指令(二) 实现传入自定义类名
1.创建自定义指令文件(选择器)
ng g directive directive/abc
Angular自定义指令_第3张图片
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

"'yuyu'">我是h2

我是h3

4.效果 标签上会有yuyu类
Angular自定义指令_第4张图片

Angular自定义指令(三) 实现点击变红
1.创建自定义指令文件(选择器)
ng g directive directive/abc
Angular自定义指令_第5张图片
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

"'yuyu'">我是h2

我是h3

4.效果 点击变红色
Angular自定义指令_第6张图片

你可能感兴趣的:(angular)