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 eachsubmithandler you’ve calledmarkAllAsTouched()to cover cases where users didn’ttouchone 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 theformGroupdirective. Next, we obtain a reference to theFormGroupDirectiveinstance via DI. The last thing we need to do is register thesubmitevent and callmarkAllAsTouched().
Comments
Post a Comment