angular - 如何仅从 fetch 表中为特定 id 扩展 mat-expansion-panel
问题描述
我正在制定项目清单。使用我的 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
}
});
}
解决方案
为什么不直接将你的 if 逻辑复制到模板中呢?
<mat-accordion>
<ng-container *ngFor="let item of items">
<mat-expansion-panel [expanded]="item.id === paramId" (click)="expandItem(item.id)">
// Content
</mat-expansion-pane>
</ng-container>
</mat-accordion>
TS:
paramId: string;
expandItem(id: string) {
this.paramId = id;
...
...
}
推荐阅读
- json - 如何以 JSON 格式读取 MySQL 数据
- javascript - 如何在 Node 中解析 POST 响应正文
- c# - c#:如果逗号数字的数量等于比例,Oracle/OracleDataReader 在小数点后添加额外的“0”
- mysql - Hibernate @CreationTimestamp @UpdateTimestamp 在不同的时区
- android - Android Gson - 反序列化空值与缺失值
- javascript - 无法在“FileReader”上执行“readAsBinaryString”:参数 1 不是“Blob”类型
- java - 从 base64 字符串或字节数组生成受密码保护的 PDF 并作为附件发送到电子邮件
- authentication - 刷新令牌流:环回
- c# - 全局锁定并等待是否为真
- php - 您可以在会话中存储多个数组值吗?