首页 > 解决方案 > 在 ngFor 或类似 ngForOutlet 的内部创建不可重复的结构

问题描述

如何在 ngFor 中创建一些不会重复的结构?我需要类似 ngForOutlet 的东西。我想根据某些项目属性对项目进行分组,然后将它们插入合适的 div 中。

为了更好地展示我想要实现的目标,这里有一些伪代码:

<div *ngFor="let item of someData">
    <div>
      <h4>Group A</h4>
        <div *ngForOutlet *ngIf="item.group === 'a'">
            <div>
                {{item.brand}}
                {{item.model}}
            </div>
        </div>
    </div>
    <div>
      <h4>Group B</h4>
        <div *ngForOutlet *ngIf="item.group === 'b'">
            <div>
                {{item.brand}}
                {{item.model}}
            </div>
        </div>
    </div>
  </div>

来自 A 组的所有项目都将插入到 A 组标题下的 div 中,而 B 组中的所有项目都将插入到 B 组下。

@Edit:目前我有这样的东西,但我想对它进行分组:

HTML

<div *ngFor="let item of someData">
    <app-some-card #card [brand]="item.brand"></app-some-card>
</div>

<button (click)="onClick()">test</button>

.ts

export class ParentComponent implements OnInit {
  @ViewChildren('card') cards: QueryList<SomeCardComponent>;

  someData = [{...},{...},...];

  onClick() {
    this.cards.forEach(card => {
        card.doSomething();
    }
  }
}

标签: angularngfor

解决方案


我建议您构建模型以符合您的要求。

在您的组件中,一旦您检索someData了 ,循环通过它并将项目添加到相关组。

组件.ts

someData: any[];
groupA: any[];
groupB: any[];

ngOnInit() {
  this.someData = [{
    group: 'a'    
  }, {
    group: 'b'
  }, {
    group: 'a'
  }];

  this.groupA = [];
  this.groupB = [];

  this.someData.forEach(item => {
    if (item.group === 'a') {
      this.groupA.push(item);
    } else if (item.group === 'b') {
      this.groupB.push(item);
    }
  });
}

然后在您的 HTML 中绑定到这些组就足够简单了。

组件.html

  <div>
    <h4>Group A</h4>
        <div *ngFor="let item of groupA">
            <div>
                {{item.brand}}
                {{item.model}}
            </div>
        </div>
    </div>
    <div>
      <h4>Group B</h4>
        <div *ngFor="let item of groupB">
            <div>
                {{item.brand}}
                {{item.model}}
            </div>
        </div>
    </div>

推荐阅读