【问题标题】:no render with mat-error, ng-template and *ngTemplateOutlet没有 mat-error、ng-template 和 *ngTemplateOutlet 的渲染
【发布时间】:2019-02-03 18:17:16
【问题描述】:

此代码运行良好且正常(没有 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>

但是这段代码不能正常工作(使用 ngTemplateOutlet),为什么? (就像普通的红色文本一样查看error.message):

<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>

有什么想法吗? 谢谢!

【问题讨论】:

    标签: angular angular-material ng-template ng-container


    【解决方案1】:

    就像这里提到的answer

    &lt;mat-error&gt; 元素必须是 &lt;mat-form-field&gt; 的直接子元素才能正常工作。

    就像在那个答案中一样,如果 case 是一个单独的组件,它也适用于此处:将您的容器设置在 mat-error 标记内,它会正常工作!

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

    这意味着您不需要在您的ng-template 中使用mat-error

    【讨论】:

    • 免责声明:我曾打算将此标记为重复,但我认为它与链接的问题有点不同..
    • 这是我想要的完全不同的代码。无法仅使用模板显示 mat-errors 并重用它。谢谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 2018-11-01
    • 2020-12-28
    • 2019-01-20
    • 2020-07-22
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多