首页 > 解决方案 > 为什么无法读取未定义的属性“poPanel”

问题描述

HTML 我正在添加一个有序列表,该列表循环遍历对象数组并根据按钮单击添加它们(即项目列表)

示例: 1. 项目 1 2. 项目 2 3. 项目 3

这些项目添加得很好。这里没问题,但是......当我添加一个删除每个项目的“删除功能”时,它会起作用并且实际上会删除它们,但我在控制台中收到以下错误。

无法读取未定义的属性“poPanel”

<ol class="panelNumbers">
    <li *ngFor="let POpanel of POpanelList">
      <button class="removePObtn" (click)="removePO(poPanel)"><span class="k-icon k-i-close-circle k-i-x-circle" *ngIf="showClose"></span></button>
      <app-po-panels></app-po-panels>
    </li>
  </ol>

.TS

在这里,我为 POpanelList 设置了一个空数组,每个项目都被推送到数组中,但是当我尝试删除面板时,我在 removePO 函数中的 poPanel 上得到一个未定义的值

 async ngOnInit() {
        await this.getText();
        this.POpanelList = [];
    }

    /*Adding and Removing PO and SO Panels*/
    addPO() {
        this.POpanelList.push(
            { poPanel: this.newPoPanel }
        );
        this.showClose = true;
    }

    removePO(poPanel) {
        for (let i = 0; i < this.POpanelList.length; i--) {
            if (this.POpanelList[i]['poPanel'] === poPanel) {
                this.POpanelList.splice(i, 1);
            }
        }

        this.showClose = false;
    }

标签: htmltypescriptangular8

解决方案


当您执行removePOfor 循环时,将开始于i=0和下一个递减i--导致i等于-1. 由于不能存在负数组索引this.POpanelList[-1]将返回undefinedthis.POpanelList[-1]['poPanel']导致您的错误:

Cannot read property 'poPanel' of undefined

我相信解决方法是i--i++你的循环中改变

    removePO(poPanel) {
        for (let i = 0; i < this.POpanelList.length; i++) {
            if (this.POpanelList[i]['poPanel'] === poPanel) {
                this.POpanelList.splice(i, 1);
            }
        }
        this.showClose = false;
    }

推荐阅读