ebakunin ebakunin - 26 days ago 10
AngularJS Question

Using FormBuilder to highlight a pristine but invalid form

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?

Answer

There's a function .markAsDirty() on anything that implements the AbstractControl interface. So, in your onSumbit():

public onSubmit(): void {
    this.myFormGroup.markAsDirty();
    console.info('is the form pristine?', this.myFormGroup.pristine);
    console.info('is the form valid?', this.myFormGroup.valid)
}

Forked plunker: http://plnkr.co/edit/k8iXCLyKIIm8QN1wgMVg?p=preview