no render with mat-error, ng-template and *ngTemplateOutlet

Issue

This code is working fine and properly (without ngTemplateOutlet):

<mat-form-field [formGroup]="formGroup">
    <input matInput type="text"
        [formControlName]="fControlName"
    >
  <ng-container *ngIf="isShowErrors()" ngProjectAs="mat-error">
    <ng-container *ngFor="let error of showSMErrors" >
      <mat-error>{{ error.message }}</mat-error>
    </ng-container>
  </ng-container>
</mat-form-field>

But this code isnt working properly(with ngTemplateOutlet), why? (just see the error.message like a normal red color text):

<mat-form-field [formGroup]="formGroup">
    <input matInput type="text"
        [formControlName]="fControlName"
    >
  <ng-container *ngTemplateOutlet="showErrorsTemplate"></ng-container>
</mat-form-field>

<ng-template #showErrorsTemplate ngProjectAs="mat-error">
  <ng-container *ngIf="isShowErrors()" >
    <ng-container *ngFor="let error of showSMErrors" >
      <mat-error>{{ error.message }}</mat-error>
    </ng-container>
  </ng-container>
</ng-template>

Any ideas?
Thanks!

Solution

Just like mentioned here in this answer:

The <mat-error> elements need to be direct children of <mat-form-field> in order to work properly.

So like in that answer, where case being a separate component, it also applies here: Set your container inside the mat-error tag and it will work just fine!

<mat-form-field [formGroup]="formGroup">
  <input matInput type="text" [formControlName]="fControlName">
  <mat-error>
    <ng-container *ngTemplateOutlet="showErrorsTemplate"></ng-container>
  </mat-error>
</mat-form-field>

which then means you don’t need to use mat-error inside your ng-template.

Answered By – AT82

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.