【问题标题】:How to expand mat-expansion-panel for specific id only from the fetch table如何仅从 fetch 表中为特定 id 扩展 mat-expansion-panel
【发布时间】:2018-12-23 09:30:35
【问题描述】:

我正在开发一个项目列表。使用我的 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
        }
    });
}

【问题讨论】:

    标签: angular typescript angular-material-6


    【解决方案1】:

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

    【讨论】:

    • 但是如果该项目不在获取记录列表中怎么办。因为记录可以是 100 0,我一次获取 30 条记录。
    • @darky 抱歉,我不是说将 if/else 逻辑完全移到模板中。本质上,您可以在模板中检查 id,并且通过将 id 分配给变量,TS 可以保持不变。
    猜你喜欢
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多