C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Angular 7 FormsAngular forms are used to handle user's input. We can use Angular form in our application to enable users to log in, to update profile, to enter information, and to perform many other data-entry tasks. In Angular 7, there are 2 approaches to handle user's input through forms:
Both approaches are used to collect user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes. Reactive Forms vs. Template-driven FormsBoth Reactive forms and Template-driven forms manage and process data differently. Each offers different advantages. Reactive Forms
Template-driven Forms
Difference between Reactive Forms and Template-driven Forms
Similarity between Reactive Forms and Template-driven FormsThere are some building blocks which are shared by both reactive and template-driven forms:
Form Model SetupForm model setup is used to track value changes between Angular forms and form input elements. Let's take an example to see how the form model is defined and created. Form model setup in Reactive formsSee the below component with an input field for a single control implemented using reactive forms. import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-reactive-favorite-color', template: ` Favorite Color: ` }) export class FavoriteColorComponent { favoriteColorControl = new FormControl(''); } In reactive forms, the form model is the source of truth. The source of truth provides the value and status of the form element at a given point in time. Here, in the example above, the form model is the FormControl instance. In reactive forms, the form model is explicitly defined in component class. After that the reactive form directive (here, it is: FormControlDirective) links the existing FormControl instance to a specific form element in the view using a value accessor (ControlValueAccessor instance). Form model setup in Template-driven FormsSee the same above component with an input field for a single control implemented using template-driven forms. import { Component } from '@angular/core'; @Component({ selector: 'app-template-favorite-color', template: ` Favorite Color: ` }) export class FavoriteColorComponent { favoriteColor = ''; } In template-driven forms, the source of truth is template itself. The form model abstraction promotes simplicity over structure. The template-driven form directive NgModel creates and manages the FormControl instance for a given form element. It's less explicit, but it removes the direct control over the form model.
Next TopicData Flow in Angular 7 Forms
|