working with angular materials mat-form-field
and reactive forms. In a project I have a recurring pattern that looks like this
// ts
this.formGroup = this.formBuilder.group({
name: ['', ServerValidation]
})
<!-- html -->
<div [formGroup]="formGroup">
<mat-form-field>
<input
matInput
formControlName="name"
[placeholder]="'Name'"
name="name"
/>
<mat-error
*ngIf="
formGroup
.get('name')
.hasError('serverValidation')
"
>
{{
formGroup
.get("name")
.getError("serverValidation")
}}
</mat-error>
</mat-form-field>
</div>
This is a high level - accepting that I can receive validation errors from the server - how can i repeat this http template pattern in a component? I have a hunch that I should utilise ControlValueAccessor - but do not know how to do so.
The implementation I imagine might look something like this
<!-- html -->
<div [formGroup]="formGroup">
<serverValidatedInput formControlName="'name'">
<mat-error>error message for client side validation</mat-error>
</serverValidatedInput>
</div>
So essentially I want to use this custom component like a regular material input (more-or-less), except that it comes with the server validation error by default. Could anyone give me some direction here - thanks. :)
There are two ways to do this - an easy way and a difficult way. The difficult way is to implement
ControlValueAccessor
and this buys you more flexibility in how the component can be used. The easy way is to just pass things through your component to the actual form elements inside. If you don't need flexibility in how this component is used, take the easy way.First though, you need to get away from the idea of using
mat-error
outside ofmat-form-control
. It simply won't work, and you don't need it to work. Leave it inside the form field and provide the content for it instead. Along with that, apply your error logic to the content ofmat-error
, not to themat-error
itself. And remember that you don't need logic to displaymat-error
- form field automatically takes care of that when the form control has an error. You only need logic to determine what the error content should be.A simple wrapper for
mat-form-field
would look something like this:my-form-field.html
my-form-field.ts
Usage
custom-form-field-example.html
custom-form-field-example.ts