首页 > 解决方案 > 如何仅从 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
        }
    });
}

标签: angulartypescriptangular-material-6

解决方案


为什么不直接将你的 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;
    ...
    ...
}

推荐阅读