Angular - Material - Mat-Error

Angular – mat-error

Mat-error is a control tuned to display UI errors.

Here’s a sample

1
2
3
4
5
6
7
8
9
10
11
12
13
<div mat-dialog-content>
<form [formGroup]="policyTypeCodeForm" >
<mat-form-field class="full-width">
<input
matInput
placeholder="Code"
formControlName="code"
required>
<mat-error *ngIf="errorFormData?.Code">
{{errorFormData?.Code}}
</mat-error>
</mat-form-field>
:

What I have learned, is that it will only fire if the control is considered an error. For that to happen the control needs to fail input validators. So I have code similar to the following:

In the declaration section of the .ts class

1
2
3
4
5
6
7
8
9
10
policyTypeCodeForm = this.formBuilder.group ( {
id: [''],
code: ['', [
Validators.required,
Validators.maxLength(8)]],
description: ['', [
Validators.required,
Validators.maxLength(100)]],
isActive: ['']
})

I think the form [formGroup] associates the form to the form builder group. The input tag, the formControlName=”code” is what binds the form field to the validators associated to that control (required, maxLength)

BTW, the save button starts like this

1
2
3
4
5
6
7
8
  public savePolicyTypeCode() { 
let policyTypeCode: PolicyTypeCode = {
id: this.isAddForm() ? null : this.policyTypeCodeForm.controls.id.value,
code: this.policyTypeCodeForm.controls.code.value,
description: this.policyTypeCodeForm.controls.description.value,
isActive: (this.policyTypeCodeForm.controls.isActive.value == 1 ? true : false)
}
:

So I grab the values from the form, and put them into a PolicyTypeCode control.

References: