2

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!

Edric
  • 24,639
  • 13
  • 81
  • 91
Szorba
  • 85
  • 6

1 Answers1

5

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.

AT82
  • 71,416
  • 24
  • 140
  • 167
  • Disclaimer: I was on the fence of marking this as a duplicate, but I saw it as bit different question than the one linked.. – AT82 Feb 03 '19 at 20:41
  • Its a totally different code what i wanted. Cannot possible to show only mat-errors with template and reuse it.. Thank you the answers! – Szorba Feb 03 '19 at 21:47