Binding in Angular
There are some basic types of binding used in Angular 5. I have listed some types of binding below,
- Event Binding
- Two-way Binding
- Template reference variable
Event Binding
There are multiple DOM events that can be used like click, key up, keypress, mouse over etc. Events are simply the actions taken by the user and can be of any type. Event binding is used to handle the DOM action raised by a user. Let’s see a simple example of event bindings.
In app.component.html,
- <button (click)="MyEventBind($event)">Event Binding</button>
In app.component.ts
- MyEventBind(e)
- {
- console.log(e);
- alert("This is Event Binding in Angular 5.");
- }
Our output will be,
This is Event Binding in Angular 5.
In the above example, on button (click) or on-click event, we have displayed alert message and logged a mouse event.
You can try this example of event binding for multiple events which are used for multiple operations.
Two-way binding
Two-way binding is an important feature of Angular 5. It automatically reflects the changes in the user interface (UI), i.e., View from Model. Here, we need to use [(ngModel)] or bindon-ngModel to bind the data. It is difficult in other languages to achieve these functionalities. We have to import FormsModules to achieve two-way binding.
Let’s see the below example.
In app.component.html,
- <input type="text" [(ngModel)]="txteventbinding">
- <button (click)="Test()">Test</button>
In app.component.ts,
- txteventbinding = '';
- Test()
- {
- alert(this.txteventbinding);
- }
Our output will be,
This is sample text
Template reference variable
This shows that the whole element properties can be accessed by using “#” or “ref” keyword.
Let’s see the below example.
In app.component.html,
- <input type="text" #text1>
- <button (click)="TemplateTest(text1.value)">Template Test</button>
In app.component.ts,
- TemplateTest(strstring)
- {
- alert(strstring);
- }
Our output will be,
This is template text.