Angular Two Way Binding
In my last 2 posts I went through the event binding and property binding syntax in Angular 2. Event binding flows from the component’s template to the model and property binding flows in the opposite direction from the model to the template.
Event and property binding are one-way binding. Two-way binding is where the data flows in both directions between the component’s template and model. Given that event binding uses () syntax and property binding uses [] syntax it makes sense 2 way binding uses [()] syntax!
The ngModel directive allows us to do 2 way data binding. In the following example the criteria component property is bound to the search input’s value in both directions …
import { Component } from "angular2/core";
import { NgClass } from "angular2/common";
@Component({
selector: "namesearch",
template: `
<input
type="search"
placeholder="enter criteria"
[(ngModel)]="criteria"
/><button (click)="doSearch()">Search</button>
`,
directives: [NgClass]
})
export class NameSearchComponent {
public criteria: string;
constructor() {
// set criteria to the users last criteria
// use a setTimeout() in this simple example
setTimeout(() => {
this.criteria = "fred";
}, 1000);
}
doSearch() {
console.log(this.criteria);
}
}
If you to learn more about TypeScript, you may find my free TypeScript course useful: