I am using following code to set error in mat form field:
<mat-form-field appearance="fill">
<mat-label> {{ Email }}</mat-label>
<input formControlName="email">
<mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
<mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}</mat-error>
</mat-form-field>
now I want to add another error when the form loads. I have a flag in ngOnInit() when it is true I want to show the error. Adding third mat-error , the error is not visible. I went through stackoverflow and tried following:
ngOnInit() {
formData.form.controls['email'].setErrors({'flag': true});
}
and adding following code in html
<mat-form-field appearance="fill">
<mat-label> {{ Email }}</mat-label>
<input formControlName="email">
<mat-error *ngIf="service.form.get('email').hasError('maxlength')">{{ 'Display.messageLength' }}</mat-error>
<mat-error *ngIf="service.form.get('email').hasError('required')">{{ 'Display.requiredMessage' }}
<mat-error *ngIf="!email.valid">{{email.errors| json}">{{ 'Display.requiredMessage' }}
</mat-error>
</mat-form-field>
My service code is as follows:
form: FormGroup = new FormGroup({
email: new FormControl('', [Validators.maxLength(10), Validators.required]),
});
Still not getting anything when the page loads. How can I do that?