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

我有点困惑。

看看这个简单的指令:

 @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 看起来像这样:

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

产出将是:

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

如果我从 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将永远不需要想知道是否或如果不,我认为方括号 []应该始终存在。不是吗?

47652 次浏览

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

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

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".

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

The brackets tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string. It does not evaluate the string!

Don't make the following mistake:

    <!-- ERROR: HeroDetailComponent.hero expects a
Hero object, not the string "currentHero" -->
<hero-detail hero="currentHero"></hero-detail>

check: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#property-binding

binding [] is for objects, without it the value is string. Be careful about types.

In the code

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

you have tried to bind the object, but the object is not available, thus it's value is undefined. On the other hand if you remove binding then the object is gone, you have only a string value assigned to the property.

If you write <img [src]="heroImageUrl"> it means that the right-hand side heroImageUrl is a template expression.

The simple difference between [myText]="abc" and myText="abc" is that in former you are asking angular to set the target PROPERTY myText using the template expression abc, while in the latter you setting the target property called myText using the string 'abc'.

Let's understand a little more about HTML.

In HTML you can define an element like this.

<input type="text" value="Bob">

input is an element whose attributes are type and value. When your browser parses this, it will create a DOM entry (an object) for this element. The DOM entry will have some properties like align, baseURI, childNodes, children etc. So, that's the difference between HTML attributes and DOM properties See reference. Sometimes the attribute and property have same names which causes confusion. For above input tag, it has the attribute value = Bob and also has a property value that will have the value of whatever you type in the text box. In summary, attribute is what you define about the tag, and property is what gets generated in the DOM tree.

In the world of Angular, the only role of attributes is to initialize element and possibly directive state. When you write a data binding, you're dealing exclusively with properties and events of the target object. HTML attributes effectively disappear.

So to summarize, in <div [myDirective]="myDefaultText" [myEnabled]="true" [myText]="abc"></div> you essentially are saying that:

  1. apply the directive myDirective to my div element.
  2. bind the variable myEnabled to the expression on the right. The expression says true, so the value of myEnabled is true.
  3. bind the variable myText to the expression on the right. The expression says abc. Is there any abc defined? No, so the expression evaluated to undefined.

From Angular guide on property binding:

The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value.

This is the latest update for Angular 13.

Let's take an example...

Suppose we have an input variable named carImage, which will contain the dynamic URL value passed from the parent.

@Input() carImage = '';

Scenario 1 - With the square brackets

<img [src]="carImage"></img>

In this case, whatever the value the carImage variable holds will be assigned to the src attribute of img. This is the property binding, where we can set the values for attributes dynamically.

Scenario 2 - Without the square brackets

<img src="carImage"></img>

In this case, the string carImage will be directly assigned to the src attribute, hence Angular will not be able to display the image since it is an invalid URL.

To make it work, you have to assign a valid URL, as shown below.

<img src="http://demo/carImage.jpg"></img>