【问题标题】:Angular 7 - Nested <ng-template> label doesn't workAngular 7 - 嵌套 <ng-template> 标签不起作用
【发布时间】:2019-06-25 15:22:58
【问题描述】:

我的代码如下:

<h2>{{ commentTitle }}</h2>

<div *ngIf="errorHappened; then displayError else displayComments">
  <div *ngIf="comments == undefined || comments.length == 0; then noComments else commentsList"></div>
</div>

<ng-template #displayError>
  <div class="alert alert-danger">An error has occurred. Please try again.</div>
</ng-template>

<ng-template #displayComments>
  <ng-template #commentsList>
    <ul>
      <li *ngFor="let comment of comments">
        <div>{{ comment.user }}</div>
        <div>{{ comment.date }}</div>
        <div>{{ comment.content }}</div>
      </li>
    </ul>
  </ng-template>

  <ng-template #noComments>
    <div>No comments yet</div>
  </ng-template>
</ng-template>

<a class="btn btn-primary" (click)="openDialog()" mat-raised-button type="button">Add new comment</a>

谁能帮我解释为什么嵌套的 div 在 h2 标签后不起作用?

提前谢谢你。

【问题讨论】:

  • 请添加关于具体是如何它“不起作用”的详细信息:控制台中有任何错误吗?当您使用--aot 构建时会发生什么? How to Ask
  • 这个问题甚至与 标签有关吗?你的问题是关于

    标签而不是 标签。

标签: angular angular7 angular-ng-if ng-template


【解决方案1】:

解决方法如下:

<h2>{{ commentTitle }}</h2>

<div *ngIf="errorHappened; then displayError else displayComments"></div>

<ng-template #displayError>
  <div class="alert alert-danger">An error has occurred. Please try again.</div>
</ng-template>

<ng-template #displayComments>
  <div *ngIf="comments == undefined || comments.length == 0; then noComments else commentsList"></div>
  <ng-template #commentsList>
    <ul>
      <li *ngFor="let comment of comments">
        <div>{{ comment.user }}</div>
        <div>{{ comment.date }}</div>
        <div>{{ comment.content }}</div>
      </li>
    </ul>
  </ng-template>

  <ng-template #noComments>
    <div>No comments yet</div>
  </ng-template>

  <a class="btn btn-primary" (click)="openDialog()" mat-raised-button type="button">Add new comment</a>
</ng-template>

【讨论】: