There are two types of forms in Angular.
Reactive forms define the form model in the component class. This is done using the FormGroup and FormControl classes.
// Form Component
import {FormControl, FormGroup } from '@angular/forms';
@Component({...})
export class FormComponent implements OnInit {
ngOnInit(): void {
this.wholeForm = new FormGroup({ // Create form group
firstName = new FormControl(''),
level = new FormControl('')
});
}
// Save Form Method
saveForm() {...}
}
<!-- Form Template -->
<!-- 👇 Top Level Form Directive -->
<form [formGroup]="wholeForm" (ngSubmit)="saveForm(wholeForm.values)">
<!-- 👇 Inner Form Directives -->
<input formControlName="wholeForm.firstName"/>
<select formControlName="wholeForm.level">
<option value="1">Beginner</option>
<option value="2">Intermediate</option>
<option value="3">Advanced</option>
</select>
</form>
Validation is done by functions.
In template-drive forms the form model is defined in the template. This is done using the ngModel directive. FormControl classes are still created in this approach but their creation is implicit. This type of form is simpler to write but less scalable.
<!-- Form Template -->
<!-- 👇 template variable assigned to ngForm -->
<form #wholeForm="ngForm" (ngSubmit)="saveForm(wholeForm.values)">
<!-- 👇 Inner Form Directives -->
<input [(ngModel)]="firstName"/>
<select [(ngModel)]="level">
<option value="1">Beginner</option>
<option value="2">Intermediate</option>
<option value="3">Advanced</option>
</select>
</form>
// Component
@Component({...})
export class FormComponent { // 👈 no OnInit
public firstName: string;
public level: number;
// Save Form Method
saveForm() {...}
}
Validation is done by directives.