Template driven forms with two-way binding

The alternative to Reactive forms are Template driven forms. If you're familiar with ng-model from AngularJS, you'll find that the new ngModel directive is an API compatible replacement for it.

Behind the scenes, ngModel implements a FormControl that can automatically attach itself to a FormGroup. ngModel can be used at the <form> level or individual <input> level. You can read more about ngModel at https://angular.io/api/forms/NgModel.

In the Local Weather app, I have included a commented-out component in app.component.ts named app-city-search-tpldriven. You can uncomment this component in app.component to experiment with it. Let's see how the alternate template implementation looks like:

src/app/city-search-tpldriven/city-search-tpldriven.component.html
...
<input matInput placeholder="Enter city or zip" aria-label="City or Zip"
[(ngModel)]="model.search" (ngModelChange)="doSearch($event)"
minlength="2" name="search" #search="ngModel">
...
<mat-error *ngIf="search.invalid">
Type more than one character to search
</mat-error>
...

Note the [()] "box of bananas" two-way binding syntax being used with ngModel.

The differences in the component are implemented as follows:

src/app/city-search-tpldriven/city-search-tpldriven.component.ts
import { NgModel, Validators} from '@angular/forms'
...
export class CitySearchTpldrivenComponent implements OnInit {
model = {
search: '',
}
...
doSearch(searchValue) {
const userInput = searchValue.split(',').map(s => s.trim())
this.weatherService
.getCurrentWeather(userInput[0], userInput.length > 1 ? userInput[1] : undefined)
.subscribe(data => console.log(data))
}

As you can see, most of the logic is implemented in the template, and the programmer is required to maintain an active mental model of what's in the template and the controller and switch back and forth between the two files to make changes to event handlers and validation logic.

Furthermore, we have lost the input limiting and the ability to prevent service calls when the input is in an invalid state. It is, of course, possible to still implement these features, but they require convoluted solutions and do not neatly fit into the new Angular syntax and concepts.

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

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