【问题标题】:Why am getting Cannot read property 'poPanel' of undefined为什么无法读取未定义的属性“poPanel”
【发布时间】:2020-07-01 02:17:35
【问题描述】:

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;
    }

【问题讨论】:

    标签: html typescript angular8


    【解决方案1】:

    当您执行removePO 时,for 循环将从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;
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2015-11-21
      相关资源
      最近更新 更多