何时在指令@Inputs 中使用方括号 [ ],何时不使用? [英] When to use square brackets [ ] in directives @Inputs and when not?

查看:33
本文介绍了何时在指令@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);
    }
}

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

if my html will look like this:

<div [myDirective]="myDefaultText" [myEnabled]="true"  [myText]="abc"></div>

输出将是:

myDirective string: myDefaultText real value  // good
myEnabled boolean: true                       // good
myText string: undefined                      // Why?

如果我从 myText 中删除 []:

If I REMOVE the [] from myText:

<div [myDirective]="myDefaultText" [myEnabled]="true"  myText="abc"></div>

输出将是:

myDirective string: myDefaultText real value  // good
myEnabled boolean: true                       // good
myText string: abc                            // GOOD

我也可以从 myEnabled 中删除 [] 并且它也可以工作.所以这是我的困惑 - 当我需要使用方括号 [] 时,当我不需要时,虽然我希望将要使用 myDirective 的用户永远不需要怀疑是否如果没有,我认为方括号 [] 应该始终存在.不是吗?

I can also remove the [] from myEnabled and it will work too. So here is my confusion - when I need to use square brackets [] and when not, while I want the user who is going to use myDirective will never need to wonder if or if not, I think the square brackets [] should always be there. Aren't they?

推荐答案

当你使用 [] 绑定到一个 @Input() 时,它基本上是一个模板表达式.

When you use [] to bind to an @Input(), it's basically a template expression.

以同样的方式显示 {{abc}} 不会显示任何内容(除非您实际上有一个名为 abc 的变量).

The same way displaying {{abc}} wouldn't display anything (unless you actually had a variable called abc).

如果你有一个字符串 @Input(),并且你想把它绑定到一个常量字符串,你可以这样绑定:[myText]=" 'some text'",或者简而言之,就像一个普通的 HTML 属性:myText="some text".

If you have a string @Input(), and you want to bind it to a constant string, you could bind it like this: [myText]=" 'some text' ", or in short, like a normal HTML attribute: myText="some text".

[myEnabled]="true" 起作用的原因是因为 true 是一个有效的模板表达式,当然它的计算结果为布尔值 true.

The reason [myEnabled]="true" worked is because true is a valid template expression which of course evaluates to the boolean true.

这篇关于何时在指令@Inputs 中使用方括号 [ ],何时不使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆