Difference between [] and {{}} for binding state to property?
Difference between string interpolation and property binding:
The main thing to understand it the following:
Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding.
This implies that under the hood it yields a similar outcome. However, string interpolation has one important limitation. This is that everything within string interpolation will first be evaluated (trying to find a value from the model ts file):
- if this value cannot be found there then the value within the string interpolation will be evaluated to a string.
- If this value is found in the model the value which is found gets coerced to a string and is used.
This has some implications on how you can use the 2 methods. For example:
String concatenation with string interpolation:
<img src=' https://angular.io/{{imagePath}}'/>
String interpolation cannot be used for anything else than strings
<myComponent [myInput]="myObject"></myComponent>
When myInput
is an @Input()
of myComponent
and we want to pass in an object, we have to use property binding. If we were to use string interpolation the object would be turned into a string and this would be passed in as a value for myInput
.
[]
is for binding from a value in the parent component to an @Input()
in the child component. It allows to pass objects.
{{}}
is for binding strings in properties and HTML like
<div somePropOrAttr="{{xxx}}">abc {{xxx}} yz</div>
where the binding can be part of a string.
()
is for binding an event handler to be called when a DOM event is fired or an EventEmitter
on the child component emits an event
@Component({
selector: 'child-comp',
template: `
<h1>{{title}}</h1>
<button (click)="notifyParent()">notify</button>
`,
})
export class ChildComponent {
@Output() notify = new EventEmitter();
@Input() title;
notifyParent() {
this.notify.emit('Some notification');
}
}
@Component({
selector: 'my-app',
directives: [ChildComponent]
template: `
<h1>Hello</h1>
<child-comp [title]="childTitle" (notify)="onNotification($event)"></child-comp>
<div>note from child: {{notification}}</div>
`,
})
export class AppComponent {
childTitle = "I'm the child";
onNotification(event) {
this.notification = event;
}
}
Plunker example
More details in https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax