相关疑难解决方法(0)

何时在指令@Inputs中使用方括号[],何时不使用?

我有点困惑.

看到这个简单的指令:

 @Directive({
      selector: '[myDirective]'
    })
    export class MyDirective {

      private text: string;
      private enabled: boolean;

      @Input() myDirective:string;

      @Input('myText')
      set myText(val: string) {
        this.text = val;
      }

      @Input('myEnabled')
      set myEnabled(val: boolean) {
        this.enabled = val;
      }

      ngOnInit() {

        console.log("myDirective string: " + this.myDirective);
        console.log("myText string: " + this.text); 
        console.log("myEnabled boolean: " + this.enabled);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我的HTML看起来像这样:

<div [myDirective]="myDefaultText" [myEnabled]="true"  [myText]="abc"></div>
Run Code Online (Sandbox Code Playgroud)

输出将是:

myDirective string: myDefaultText real value  // good
myEnabled boolean: true                       // good
myText string: undefined                      // Why?
Run Code Online (Sandbox Code Playgroud)

如果我删除[] myText …

typescript angular2-directives angular

43
推荐指数
6
解决办法
2万
查看次数

标签 统计

angular ×1

angular2-directives ×1

typescript ×1