1.

Explain two-way binding in Angular?

Answer»

<P>Two-way data binding was one of the most prominent selling points of Angular that made developers go WOW! Basically, two-way binding means that the changes made to the DOM (due to some events or user interactions) are reflected back in the model or application data and the changes in the data or model are reflected in the application’s view immediately. This saves developers a lot of trouble that they had to go through to keep both in sync.

LET’s have a look at an example.

TS Code.

username: string;

HTML Code

<input [(ngModel)]="username"> <p>HELLO {{username}}!</p>

If you run the above code within an Angular component, you will simply get to see a text input and a paragraph text. Try CHANGING the text in the input field. Did you see that? The text in the paragraph changes automatically, does not it?

How does that happen? Well, that’s because of two-way binding. Let’s have a look at what is happening here, step-by-step.

The ngModel directive here ensures that the username property in the class (the TS code above) is always updated when you or the user updates the input field’s value. It also ensures that if the value of the property happens to change over time because of some code executions, the changes will immediately propagate to the view and the user will see the value change in the page. 

In the above demo, the value of text in the paragraph changes because it is bound to the value of the username property which is in turn bound to the value of the input field. It all works together.



Discussion

No Comment Found