Element references

Element references allow you to attach a variable name to elements inside the template. Then you can reference those elements throughout the template, and even in code.

You use the hash symbol (#), followed by a name of your choice. This is the associated element name, which you then use elsewhere.

The following is an example of a simple usage of element references:

<input #title />
<span>{{ Title length: title.value.length }}</span>

Moreover, element references can be set to certain directives, and ngModel is one of them. Combined, you get the ngModel, associated with the element as the element reference variable, which includes the validity state, among other things.

Now change the ProductFormComponent template to display error messages, and then disable the Submit button according to the validity state:

<form #productForm="ngForm">
<div>
<label for="title">Title</label>
<input id="title" name="title" [(ngModel)]="product.title"
#title="ngModel" required minlength="3" maxlength="50" />

<span [class.hidden]="!title.errors?.required">Title is
required</span>
<span [class.hidden]="!title.errors?.minlength">
Title should be at least 3 characters long
</span>
<span [class.hidden]="!title.errors?.maxlength">
Title should be less than 50 characters long
</span>

</div>
<div>
<label for="description">Description</label>
<textarea id="description" name="description"
[(ngModel)]="product.description"></textarea>
</div>
<div>
<label for="category">Category</label>
<select id="category" name="category" [(ngModel)]="product.category"
#category="ngModel" required>
<option value=''>Select category..</option>
<option *ngFor="let c of categories" [value]="c.name">{{ c.name
}}</option>
</select>
<span [class.hidden]="category.valid">Category is required</span>
</div>
<div class="actions-panel">
<button (click)="onSubmit(true)" [disabled]="!productForm.form.valid">
Save
</button>
<button (click)="onSubmit(false)">Cancel</button>
</div>
</form>

As you can see in the preceding code, in addition to ngModel, the template uses an element reference with another directive from Angular Forms—ngForm. The element reference variable is set to the ngForm directive that tracks and monitors the form-wide validity status, which affects the submit button's disabled state.

Congratulations! You can now run the app and see the form validation function in action. It should look similar to the following screenshot:

You can read more about template-driven and reactive-style forms in the Angular documentation at https://angular.io/guide/forms and https://angular.io/guide/reactive-forms.
You can find all the client-side related code in a public GitHub repository at https://github.com/azuker/frontend-web-dev.
..................Content has been hidden....................

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