简体   繁体   English

角4,如何根据条件将元素放入一个容器或另一个容器中?

[英]Angular 4, How to put elements in one container or the other container based on condition?

Array: 阵:

this.elements = [
  {'value' : 'One', 'bool': true },
  {'value' : 'Two'}
  {'value' : 'Three'}
]

Template: 模板:

<ng-container *ngFor="let e of elements"> <div *ngIf="e.bool" style="border:1px solid red">{{e.value}}</div> <div *ngIf="!e.bool" style="border:1px solid blue">{{e.value}}</div> </ng-container>

This yields: 这样产生:

<div style="border:1px solid red">one</div>
<div style="border:1px solid blue">two</div>
<div style="border:1px solid blue">three</div>

What I want: 我想要的是:

<div style="border:1px solid red">one</div>
<div style="border:1px solid blue">two three</div>

Question: 题:

What would be the correct template syntax to create the desired layout? 创建所需布局的正确模板语法是什么? Here is a demo I started. 这是我开始的演示。 https://plnkr.co/edit/BwzMEQ05IJCGdLYNTLXA?p=preview https://plnkr.co/edit/BwzMEQ05IJCGdLYNTLXA?p=preview

The correct syntax to render the desired layout consists in loop each div. 呈现所需布局的正确语法包括在每个div循环中。

<h2>Hello {{name}}</h2>
<ng-container>
    <div style="border:1px solid red">
      <ng-container *ngFor="let e of elements">
        {{e.bool ? e.value : ''}}
      </ng-container>
    </div>
    <div style="border:1px solid blue">
      <ng-container *ngFor="let e of elements">
        {{!e.bool ? e.value : ''}}
      </ng-container>
    </div>
</ng-container>

Working plunker: https://plnkr.co/edit/6DUPRDtHpOqH9Gkf4erR?p=preview 工作中的矮人: https ://plnkr.co/edit/6DUPRDtHpOqH9Gkf4erR ? p = preview

You can also filter the array in order to have that logic outside the template. 您也可以过滤数组,以使该逻辑在模板之外。

Inside ngOnInit() ngOnInit()

    this.firstDivElements = this.elements.filter((e) => e.bool)
    this.secondDivElements = this.elements.filter((e) => !e.bool)

Inside the template 模板内

    <ng-container>
        <div style="border:1px solid red">
          <ng-container *ngFor="let e of firstDivElements">
            {{e.value}}
          </ng-container>
        </div>
        <div style="border:1px solid blue">
          <ng-container *ngFor="let e of secondDivElements">
            {{e.value}}
          </ng-container>
        </div>
    </ng-container>

Working plunker: https://plnkr.co/edit/oy1Jz2smbeIzfPszg0rv?p=preview 可以使用的插件: https ://plnkr.co/edit/oy1Jz2smbeIzfPszg0rv ? p = preview

Just as a comment: please, take in count that since Angular 2, all versions (2+) are just named angular. 就像一条评论:请记下,自Angular 2起,所有版本(2+)均被命名为angular。 There is no need to differenciate Angular 2 or Angular 4 unless you're referencing a very especific characteristic. 除非您要引用非常具体的特征,否则无需区分Angular 2或Angular 4。

Best regads. 最好的家伙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM