已解决-Angular 7-嵌套的<ng-template>标签不起作用

时间:2019-06-25 15:22:58

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

我的代码如下:

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

请问有人可以帮我解决为什么h2标签后的嵌套div无法正常工作吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

解决方案如下:

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