Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [] and {{}} for binding state to property?

Here is an template example:

<span count="{{currentCount}}"></span>
<span [count]="currentCount"></span>

Here both of them does the same thing. Which one is preferred and why?

like image 971
Narayan Prusty Avatar asked Apr 26 '16 10:04

Narayan Prusty


1 Answers

[] 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

like image 165
Günter Zöchbauer Avatar answered Oct 11 '22 16:10

Günter Zöchbauer