I want to use mat-errors to render server-side errors in my Angular 5 SPA.
This is what I've got so far, and it works
<mat-form-field class="col-6">
<input matInput formControlName="firstName">
<mat-error [hidden]="!form.controls.firstName.hasError('required')">This field is required and cannot be empty</mat-error>
<mat-error [hidden]="!form.controls.firstName.hasError('other')">Some other error</mat-error>
</mat-form-field>
Every field of the form looks similar. Input field and many mat-error tags below. There is lots of repetitive code attached to single input field. Also, adding a new error message would cause adding it in the every field that needs it.
I think it is a good space to introduce component that manages error messages, and injected with form control it decides which error to show (I want to have common error messages for all fields).
So I would like to have it this way
<mat-form-field class="col-6">
<input matInput formControlName="firstName">
<app-mat-errors [field]="form.controls.firstName"></app-map-errors>
</mat-form-field>
and in the app-mat-errors
component template have all the mat-error
code that we used to have in every single field
<mat-error [hidden]="!field.hasError('required')">This field is required and cannot be empty</mat-error>
<mat-error [hidden]="!field.hasError('other')">Some other error</mat-error>
etc....
With this approach I'm having a problem with rendering component correctly.
When put to the <app-mat-errors>
, <mat-error>
tags are embedded in app-mat-errors
tag and are not showing properly (they are not styled and visible all the time, even when there is no error)
Is there any way angular can render component wihout parent tag? Or you have any ideas how to make it working properly? Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…