【问题标题】:Angular 2+, Display a container element only if a condition applies but display the childrenAngular 2+,仅在条件适用但显示子元素时显示容器元素
【发布时间】:2018-07-25 07:54:42
【问题描述】:

我需要为 Angular 组件列表创建一个类似网格的视图,并且我需要在同一行中最多显示 4 个组件。

我发现的最接近的问题是这个:Angular 2 NgIf, dont render container element on condition but show its child elements

但如果容器只有一个孩子,它就可以工作。这也是我首先尝试的(我知道我可以使用 else 案例):

<ng-container *ngFor="let pair of responsePair;let i = index">
  <ng-container *ngIf="i % 4 == 0">
    <div class="row">
      <app-report-tile></app-report-tile>
    </div>
  </ng-container>

  <ng-container *ngIf="i % 4 != 0">
    <app-report-tile></app-report-tile>
  </ng-container>
</ng-container> 

仅为第 4 个元素打印行容器,我需要接下来的 3 个子组件成为该行容器的一部分。

有没有办法在某些情况下不渲染 HTML 元素?

【问题讨论】:

  • 你可以为此创建 stackblitz 示例吗??
  • 这不是特例,我只是在某些情况下需要隐藏容器。

标签: angular typescript


【解决方案1】:

据我了解您的要求:

stackblitz

HTML:

<ng-container *ngFor="let pair of responsePair;let i = index">
    <div *ngIf="i%4 == 0" class="row">
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
        <div class="col">
            <hello></hello>
        </div>
    </div>
</ng-container>

【讨论】:

  • 这个看起来不错,我现在就试试。但是这样会不会产生重复的组件? “i”变量什么时候递增?
  • 不要使用 'i' 它会生成重复的,我只使用了。
  • 就我而言,我需要使用索引。我将使用“i”变量从 Array 中获取组件。你的例子很好,对于每一行我使用 i+1、i+2、i+3,但是我需要以某种方式在索引中添加 +3。
  • 是的,你可以做到这一点,这就是我采用索引方案的原因
  • 我需要搜索是否可以。
【解决方案2】:

UnluckyAj给了我一个想法,我自己找到了答案,我只创建了1行并提前获取了下一个元素:

<ng-container *ngFor="let pair of responsePair;let i = index">
  <ng-container *ngIf="i % 4 == 0">
    <div class="row">
      <app-report-tile *ngIf="responsePair[i] !== undefined" [data]="responsePair[i]" ></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 1] !== undefined" [data]="responsePair[i + 1]"></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 2] !== undefined" [data]="responsePair[i + 2]"></app-report-tile>
      <app-report-tile *ngIf="responsePair[i + 3] !== undefined" [data]="responsePair[i + 3]"></app-report-tile>
    </div>
  </ng-container>
</ng-container>

确保在每个组件上使用 *ngIf 以避免异常

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    相关资源
    最近更新 更多