Using FormBuilder in Angular 2 to highlight dirty and invalid fields is easy. However, you can submit a pristine but invalid form without ever changing the fields to dirty.
For example, this code will show that when you submit the form without ever touching the inputs the FormGroup will be invalid but .ng-pristine will remain on the text field. This means that the user will not be notified that something is wrong with the text field.
@Component({
template: `
<form [formGroup]="myFormGroup">
<input type="text" formGroupName="foo">
<input type="submit" value="Submit" (click)="onSubmit()">
</form>
`,
styles: [`
.ng-dirty.ng-invalid { border: 2px solid red; }
`]
})
export class AppComponent {
public myFormGroup: FormGroup;
constructor(private _fb: FormBuilder) {
this.myFormGroup = this._fb.group({
foo: ['', Validators.required]
});
}
public onSubmit(): void {
console.info('is the form pristine?', this.myFormGroup.pristine);
console.info('is the form valid?', this.myFormGroup.valid);
}
}
Example in Plunker.
How can you change a pristine FormControl to dirty when submitting a form?