Skip to content Skip to sidebar Skip to footer

Angular Custom Validator Apply Template For Repetitive Code

I have multiple input fields where almost same validation is required. Is there any way to reduce repetitive HTML code for displaying error. My code is as below <

Solution 1:

You can create a component with input properties something like

export class YourCustomComponent{
@Input() control:FormControl;
@Input() errMessages:any;//it should be an object like {required:'desc is req'}constructor(){
}

}

in html

<div *ngIf="control.invalid && (control.dirty || control.touched)"class="alert alert-danger"><div *ngIf="control.errors.required">
                   errMessages.required
                  </div>
                  ......so on
         </div>

Then use it under your input like

<your-custom-component [control]="desc" [errMessages]="{required:'desc is required'}"></your-custom-component>

Post a Comment for "Angular Custom Validator Apply Template For Repetitive Code"