Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/Material mat-form-field custom component - matSuffix in ng-content

My idea was to have basic component providing some functionality and add matSuffix and <mat-hint> options as necessary. The component HTML is:

<mat-form-field>
  <textarea matInput matTextareaAutosize matAutosizeMinRows="1" matAutosizeMaxRows="3"
    [placeholder]="placeholder" [formControl]="inputField"></textarea>
  <ng-content></ng-content>
</mat-form-field>

However when I am using this in parent HTML template as

<my-component ...>
  <button matSuffix ...><mat-icon>something</mat-icon></button>
  <mat-hint>Press Ctrl+Enter to finish input</mat-hint>
</my-component>

The button and hint is rendered inside mat-form-field and not as suffix or hint.

Anyone, please?

Edit: Stackblitz

like image 993
PeS Avatar asked May 28 '18 23:05

PeS


1 Answers

The selector based children of MatFormField need to be direct children - they can not be nested inside other components. As an alternative, you can do something like this:

<mat-form-field>
  <textarea matInput matTextareaAutosize matAutosizeMinRows="1" matAutosizeMaxRows="3"
    [placeholder]="placeholder" [formControl]="inputField"></textarea>
  <span matSuffix>
    <ng-content select="[suffix]"></ng-content>
  </span>
  <mat-hint>
    <ng-content select="[hint]"></ng-content>
  </mat-hint>
</mat-form-field>

...

<my-component ...>
  <span suffix><button><mat-icon>something</mat-icon></button></span>
  <span hint>Press Ctrl+Enter to finish input</span>
</my-component>
like image 58
G. Tranter Avatar answered Nov 14 '22 21:11

G. Tranter