我正在制定项目清单。使用我的html文件中的循环,将每个项目提取并放置在mat-expansion-panel中。
我想做的是:如果某个项目的ID传递到URL中(例如:example.com/items/id),则该ID的扩展面板 将仅展开,如果未找到该项目,则它将查找该项目的数据库并将其推入当前项目列表中,然后将再次调用相同的过程,这次将找到并扩展该项目。
我目前的方法与此逻辑类似。
我的.HTML文件:
<mat-accordion>
<mat-expansion-panel *ngFor="let item of items" [expanded]="">
// Content
</mat-expansion-pane>
</mat-accordion>
我的Component.ts文件:
expandItem(id: string) {
this.getAllItems(); // calling list of all items and saving it into 'items' variable.
for (const item of this.items) {
if (item.id === id) {
console.log('Found item into the list');
// expand that expansion panel somehow -_-'
} else {
console.log('not found in the list');
// Now fetch that item from Database.
this.FunctionService.getItem(id).subscribe((data: {}) => {
this.item = data;
}, (err) => {
console.log(err);
});
if (this.item) {
// if found then push this item inside the list and call this function again so that this time item will be found and gets expanded.
this.items.push(this.item);
this.expandFunction(id);
}
}
}
}
ngOnInit() {
this.route.params.subscribe((params) => {
if (params['id']) {
this.expandItem(params['id']); // call function which contains the expand panel code
} else {
this.getAllItems(); // otherwise call all items
}
});
}
答案 0 :(得分:1)
为什么不将您的if逻辑复制到模板?
<mat-accordion>
<ng-container *ngFor="let item of items">
<mat-expansion-panel [expanded]="item.id === paramId">
// Content
</mat-expansion-pane>
</ng-container>
</mat-accordion>
TS:
paramId: string;
expandItem(id: string) {
this.paramId = id;
...
...
}