angular - 在 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();
}
}
}
解决方案
我建议您构建模型以符合您的要求。
在您的组件中,一旦您检索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>
推荐阅读
- selenium - ExpectedConditions.presenceOf 和 element.isPresent 有什么区别
- c# - selenium.WebDriverException:未知错误:Runtime.evaluate 在参数列表后抛出异常:SyntaxError:missing )。以前的ans没有解决
- urlencode - 呈现 Jasper 报告时出现授权错误
- android - DialogFragment - 设置状态栏颜色在某些设备上不起作用
- php - mac和windows上传文件名编码不同的问题
- typescript - Typescript Fetch API 返回 Promise
或承诺 - python - while循环中的空白图
- python - 如何从模型的视图访问序列化器字段?
- java - hibernate-orm-panache-resteasy: {"error":"id to load is required for loading","code":500} running a native build
- azure - 是否可以将 Azure Dev Spaces 与 API 管理一起使用?