Working with Angular Forms validation you’ve probably used the following code in your HTML to show errors:
<form [formGroup]="group" (ngSubmit)="submit()"> <input type="email" formControlName="email"> <p *ngIf="group.get('email').hasError('required') && group.get('email').touched"> This field is required </p> <input type="password" formControlName="password"> <p *ngIf="group.get('password').hasError('required') && group.get('password').touched"> This field is required </p> <button type="submit">Submit</button> </form>
And in eachsubmit
handler you’ve calledmarkAllAsTouched()
to cover cases where users didn’ttouch
one of the fields:
@Component() export class AppComponent { group = new FormGroup({ email: new FormControl('', Validators.required), password: new FormControl('', Validators.required) }); submit() { this.group.markAllAsTouched(); if(this.group.valid) { ... } } }We can automate this process by creating a directive that seamlessly does the work for us:import { Directive, Self, HostListener } from '@angular/core'; import { ControlContainer } from '@angular/forms'; @Directive({ selector: 'form[formGroup]' }) export class MarkFormTouchedDirective { @HostListener('submit') onSubmit() { this.container.control.markAllAsTouched(); } constructor(@Self() private container: ControlContainer) { } }First, we target forms that have theformGroup
directive. Next, we obtain a reference to theFormGroupDirective
instance via DI. The last thing we need to do is register thesubmit
event and callmarkAllAsTouched()
.
Comments
Post a Comment