Two-way data binding

We already mentioned it a number of times as one of the most convenient and widely-known features of Angular, as well as in many other reactive frameworks out there. Nonetheless, before going further, let’s ensure that we know what we’re talking about.

Two-way data binding, also known as two-way binding, means that whenever the Data Model changes, the UI changes accordingly and vice versa. To be more specific, consider the following:

  • Whenever the model is updated, the changes are immediately reflected to the views implementing it
  • Whenever a view is updated, the changes are immediately reflected in the underlying model

From a practical development perspective, two-way data binding will help us a lot, because we won’t have to manually sync the UI components with the Data Model.

The good news is, since we’re using Angular, we’re already set; our application is already equipped with fully-functional two-way data binding between two Angular components that share a data bind via the Quiz interface: the QuizListComponent and the QuizComponent. The magic lies in the way we implemented the [(ngModel)] directive within the QuizComponent template file (relevant lines are highlighted):

<div *ngIf="quiz" class="quiz">
<h2>{{quiz.Title}}</h2>
<ul>
<li>
<label>Title:</label>
<input [(ngModel)]="quiz.Title" placeholder="Insert the
title..." />
</li>
<li>
<label>Description:</label>
<textarea [(ngModel)]=" quiz.Description"
placeholder="Insert a suitable description..."></textarea>
</li>
</ul>
</div>

We can easily check this out by running the application in Debug mode, then selecting a quiz and changing its Title property using the input textbox provided by the QuizComponent. We can easily note how any change will be immediately reflected in the QuizListComponent accordingly:

As we already said, all of these things are happening on the client-side only, so order to persist them through the server Model, we will need to implement a fully-featured Data Source, which is something we will do in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.249.220