Angular - 2.14 Propriété Binding
String interpolation is a great way to output data into a template, but Angular gives us another tool to push values toward the DOM: property binding. Property binding lets you bind a component class member to a native HTML element property using square brackets around the property name. In many cases interpolation and property binding are interchangeable, but property binding shines when you need to set a property that does not naturally accept a string - for example a boolean attribute such as disabled.
Let's go back to the server component where we manage the list of servers. We want to add a button that lets the user create a new server. The template now contains <button class="btn btn-primary">Add server</button> with Bootstrap classes for styling - nothing Angular-specific yet. We also move the template back to an external file using templateUrl: './servers.component.html'. The button shows up but does nothing yet because we have not learned event binding.
Bind disabled to a class property
- In the class we declare
allowNewServer = false. - In the template we bind the native
disabledproperty:<button [disabled]="!allowNewServer">Add server</button>. - Hard-coding
disableddirectly would lock the button forever - property binding makes it react to data.
To prove that the binding is dynamic, we add a setTimeout inside the constructor. The constructor runs when Angular instantiates the component, so we can write setTimeout(() => { this.allowNewServer = true; }, 2000);. The ES6 arrow function syntax may look unusual but it works like a regular function and preserves the surrounding this, which is exactly what we want.
Reload the application: at first the button is greyed out because allowNewServer is false. After two seconds, the timer fires, the property becomes true, and the button automatically becomes clickable. We did not write any DOM manipulation code - Angular's property binding listens to the class member and keeps the DOM in sync. This is the essence of property binding: link any HTML element property to a TypeScript expression and let Angular's change detection do the rest, making the interface dynamic and reactive.