Template-Driven forms

If you come from AngularJS, there's a high chance that the Template-Driven approach will ring a bell or two. As the name implies, Template-Driven forms host most of the logic in the template code; working with a Template-Driven form means to build the form in the .html template file, to data bind the various input fields to a ngModel instance, and use a dedicated ngForm object, related to the whole form and containing all the inputs, each one of them being accessible through their name, to perform the required validity checks.

To better understand it, here's how a Template-Driven form looks:

<form novalidate autocomplete="off" #form="ngForm">

<input type="text" name="title" value="" required
placeholder="Insert a title..."
[(ngModel)]="quiz.Title" #title="ngModel"
/>

<span *ngIf="(title.touched || title.dirty) &&
title.errors?.required">
Title is a required field: please enter a valid title.
</span>

<button name="btnSubmit"
(click)="onSubmit()"
[disabled]="form.invalid">
Submit
</button>

</form>

As we can see, we can access any element, including the form itself, with some convenient aliases--the attributes with the # sign--and check for their current states to create our own validation workflow. These states are provided by the framework and will change in real time depending on various things; touched, for example, becomes TRUE when the control has been visited at least once, dirty, as opposite of pristine, means that the control value has changed, and so on. We used both of them in the preceding example, because we want our validation message to be shown only if the user moves his focus to the <input name="qName"> and then goes away, leaving it blank by either deleting its value or not setting it.

These are Template-Driven forms in a nutshell; let's try to summarize the pros and cons of this approach:

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

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