MatFormField projection with ng-content

807 views
Skip to first unread message

Francesco Rigotti

unread,
Jul 3, 2018, 10:05:12 AM7/3/18
to angular-material2
Hi,

at the moment, when using a mat-form-field and mat-error, the name of the control needs to be repeated three times:


<mat-form-field>
<input type="text" formControlName="aField" matInput placeholder="some">
<mat-error *ngIf="fields.get('aField').invalid">
    {{fields.get('aField').errors | customErrorPhrasePipe}}
</mat-error>
</mat-form-field>
  1. bind the control the input
  2. check whether or not to instantiate a mat-error
  3. get the field errors to convert them to proper messages for the user
To remove this very typo-prone boilerplate I authored a very simple component:

<mat-form-field>
<ng-content></ng-content>
<mat-error *ngIf="invalid">{{ errors | customErrorsPhrasePipe}}</mat-error>
</mat-form-field>

(invalid and errors are component properties computed using a combination of a viewProvided FormGroupDirective and the name of the field passed as input property by users of the component as follows:

<app-mat-form-field [field]="'aField'">
   <input type="text" formControlName="aField" matInput placeholder="some">
</app-mat-form-field>

This allows to remove one repetition of the field name and to hide the mat-error related code.

Sadly this does not work as mat-form-field complains that it must contain a MatFormFieldControl.

I found this issue on Github, which does not seem active.

First I'd like to know what is your preferred discussion tool: Github or this group?

Second, are there any plans to tackle this by your side?
If not, why? AKA what is a better way as clients of the library to use mat-form-field?

Thanks a lot for the awesome things you are building!!!





Reply all
Reply to author
Forward
0 new messages