Encountering an issue where the mat-error
is not functioning as intended.
A custom component was created to manage errors, but it is not behaving correctly upon rendering.
Here is the relevant page code:
<mat-form-field appearance="outline">
<input matInput placeholder="Enter your email" formControlName="ip" required>
<app-form-field-error [form-control]="resourceForm.get('ip')"></app-form-field-error>
</mat-form-field>
This is the HTML for the custom component:
<mat-error >{{errorMessage}}</mat-error>
And here is the TypeScript code for the custom component:
import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-form-field-error',
templateUrl: './form-field-error.component.html',
styleUrls: ['./form-field-error.component.css']
})
export class FormFieldErrorComponent implements OnInit {
@Input('form-control')
formControl: FormControl;
constructor() {}
ngOnInit() {}
public get errorMessage(): string | null {
if (this.mustShowErrorMessage()) {
return this.getErrorMessage();
} else {
return null;
}
}
private mustShowErrorMessage(): boolean {
return this.formControl.invalid && this.formControl.touched;
}
private getErrorMessage(): string | null {
if (this.formControl.errors.email) {
return 'Invalid email format';
} else if (this.formControl.errors.minlength) {
const requiredLength = this.formControl.errors.minlength.requiredLength;
return `Must be at least ${requiredLength} characters long`;
} else if (this.formControl.errors.maxlength) {
const requiredLength = this.formControl.errors.maxlength.requiredLength;
return `Must not exceed ${requiredLength} characters`;
}
}
}
Expected outcome: http://prntscr.com/o35s9k
Current result: http://prntscr.com/o35shk