ngModel

One of the fundamental building blocks for template-driven forms is ngModel, and you will find it being used throughout our form. One of the primary roles of ngModel is to support two-way binding between user input and an underlying model. With such a setup, changes in the model are reflected in the view, and updates to the view too are reflected back on the model. Most of the other directives that we have covered so far only support one-way binding from models to views. ngModel goes both ways. But, be aware that it is only available within NgForm for use with elements that allow user input.

As you know, we already have a model that we are using for the Workout page, WorkoutPlan. Here is the WorkoutPlan model from model.ts:

export class WorkoutPlan { 
  constructor( 
    public name: string, 
    public title: string, 
    public restBetweenExercise: number, 
    public exercises: ExercisePlan[], 
    public description?: string) { 
  } 
totalWorkoutDuration(): number{ 
 . . . [code calculating the total duration of the workout]. . . 
} 

Note the use of the ? after description. This means that it is an optional property in our model and is not required to create a WorkoutPlan. In our form, this will mean that we will not require that a description be entered and everything will work fine without it.

Within the WorkoutPlan model, we also have a reference to an array made up of instances of another type of model: ExercisePlan. ExercisePlan in turn is made up of a number (duration) and another model (Exercise), which looks like this:

export class Exercise {
constructor(
public name: string,
public title: string,
public description: string,
public image: string,
public nameSound?: string,
public procedure?: string,
public videos?: Array<string>) { }
}

The use of these nested classes shows that we can create complex hierarchies of models that can all be data-bound within our form using NgModel. So throughout the form, whenever we need to update one of the values in a WorkoutPlan or an ExercisePlan, we can use NgModel to do that (the WorkoutPlan model will be represented by a local variable named workout in the following examples).

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

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