Adding shortcuts

If we take another look at our brand new validator template, we can see a certain amount of code bloat; the form.get('Title') method is called no less than five times, and all those long lines pose a serious threat to our template's readability. Is there a way to address that?

As a matter of fact, there is--whenever we feel like we're writing too much code or repeating a complex task too many times, we can create one or more helper methods within our component class to centralize the underlying logic. In our specific scenario, we can add these methods to the QuizEditComponent class:

// retrieve a FormControl
getFormControl(name: string) {
return this.form.get(name);
}

// returns TRUE if the FormControl is valid
isValid(name: string) {
var e = this.getFormControl(name);
return e && e.valid;
}

// returns TRUE if the FormControl has been changed
isChanged(name: string) {
var e = this.getFormControl(name);
return e && (e.dirty || e.touched);
}

// returns TRUE if the FormControl is invalid after user changes
hasError(name: string) {
var e = this.getFormControl(name);
return e && (e.dirty || e.touched) && !e.valid;
}

The comments are self-explanatory, so there's nothing more to say. These helper methods grant us the chance to shrink our previous validation code, as follows:

<div class="form-group"
[ngClass]="{ 'has-error has-feedback' : hasError('Title') }">
<label for="title">Quiz title:</label>
<br />
<input type="text" id="title"
formControlName="Title" required
placeholder="choose a title..."
class="form-control" />
<span *ngIf="hasError('Title')
class="glyphicon glyphicon-remove form-control-feedback"
aria-hidden="true"></span>
<div *ngIf="hasError('Title')"
class="help-block">
Title is a required field: please insert a valid title.
</div>
</div>

Much better.

Our first Reactive form is now complete; from now on, this will be our standard approach whenever we need to implement a form. However, we still have to bring the remaining form-based components--QuestionEditComponent, AnswerEditComponent, and ResultEditComponent--up to Reactive speed. Luckily enough, we'll just have to play the same music, at least for the most part.

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

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