【问题标题】:Create not repetable structure inside ngFor or something like ngForOutlet在 ngFor 或类似 ngFor Outlet 的内部创建不可重复的结构
【发布时间】:2020-04-02 20:34:54
【问题描述】:

如何在 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 组下。

@编辑: 目前我有这样的东西,但我想把它分组:

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();
    }
  }
}

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    我建议您构建模型以满足您的要求。

    在您的组件中,一旦您检索到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 中绑定到这些组就足够简单了。

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

    【讨论】:

    • 我在 ngFor 中有组件,并且项目数据在每次迭代中都传递给该组件,然后我可以拥有 ViewChildren 并轻松地从每个组件调用一个方法。如果我按照你说的做,我将需要有许多 ViewChildren 对象并遍历它们中的每一个以从每个组件调用方法
    • 这改变了问题 - 错过了一个非常重要的事实......你能用你的意思的例子来更新你的问题吗?
    • 我更新了我的问题。我也想以某种方式监听来自整个 QueryList 组件的事件并计算它们
    • 我仍然不明白为什么这会阻止您对模型中的项目进行分组?当引用分布在整个 HTML stackblitz.com/edit/angular-sukuuw 时,QueryList 仍然有效
    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2019-10-28
    • 2019-08-10
    • 1970-01-01
    • 2016-07-11
    • 2018-03-21
    相关资源
    最近更新 更多