I like has an error-component.
@Component({
selector: 'app-error',
template: `
<small class="form-text text-danger" *ngIf="(control.touched || control.dirty)
&& control.invalid && (error?control.errors[error]:true)" >
<ng-content></ng-content>
</small>`
})
export class ErrorComponent {
@Input('controlName') controlName: string;
@Input('error') error: string
@Input('control') control:any
visible: boolean = false;
constructor(@Optional() @Host() public form: FormGroupDirective) { }
ngOnInit() {
if (this.form) {
this.control = this.form.form.get(this.controlName) as FormControl
}
}
}
You can use in a formGroup, use controlName
input to indicate the control, and error
input if you has severals Validators and want discriminate
<form [formGroup]="form">
<input formControlName="email">
<app-error controlName="email" error="required">Email required.</app-error>
<app-error controlName="email" error="email">incorrect email </app-error>
</form>
form=new FormGroup({
email:new FormControl('',[Validators.required,Validators.email])
})
Or standalone, use [control]
input to indicate the control
<input [formControl]="control">
<app-error [control]="control">control required</app-error>
control=new FormControl('',Validators.required)
See the stackblitz demo