Angular Forms
Working with template-driven and reactive forms
Template-Driven Forms
import { FormsModule } from '@angular/forms';
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<input name="name" [(ngModel)]="user.name" required>
</form>
Reactive Forms Setup
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
export class AppComponent {
form = new FormGroup({
name: new FormControl('')
});
}
Reactive Forms Template
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="name">
</form>
Form Validation
import { Validators } from '@angular/forms';
name: new FormControl('', [Validators.required, Validators.minLength(3)])
Accessing Form Values
this.form.value # get all values
this.form.get('name').value # get specific value
this.form.valid # check if valid
Form Builder
import { FormBuilder } from '@angular/forms';
constructor(private fb: FormBuilder) { }
this.form = this.fb.group({
name: ['', Validators.required]
});