关于Angular directive使用的语法问题

127 阅读1分钟

源代码:

import {
  AfterViewInit,
  Component,
  Directive,
  Input,
  OnInit
} from "@angular/core";

@Directive({
  selector: "[cxFocus]"
})
export class FocusDirective implements OnInit, AfterViewInit {
  @Input("cxFocus") public config: string;

  @Input() set cxRefreshFocusOn(_switchCondition: string) {
    console.log("Jerry new value: " + _switchCondition);
  }

  constructor() {
    console.log("Jerry directive constructor");
  }

  ngAfterViewInit(): void {
    console.log("Jerry directive in ngOnInit: " + this.config);
  }
  ngOnInit(): void {
    console.log("Jerry directive in ngOnInit: " + this.config);
  }
}

@Component({
  selector: "app-root",
  template: `
    <div [cxFocus]="jerry">Hello</div>
    <div cxFocus="Jerry config">World</div>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  jerry = "Jerry Hello";
}

运行时输出:

如果cxFocus input被中括号包裹,则等号右边必须为Component的一个实例属性,否则编译会报错:

如果cxFocus不加中括号,则等号右边的字符串被当成静态字符串处理,而不是表达式。

如果需要directive根据host元素里某个属性的变化而做相应的值,一个例子:

cxFocus加上中括号之后:

去掉中括号之后:变成纯字符串了:

更多Jerry的原创文章,尽在:“汪子熙”: