首页 > 解决方案 > 材料表未反映数据源的更改

问题描述

这是我在 Stack Overflow 上的第一个问题。我会尽量具体,但我不知道如何保持简短,所以这将是一个很长的帖子。对于那个很抱歉。我保证我在问之前搜索并尝试了很多东西,但我现在有点迷路了。

我正在 Angular 6 中开发一个简单的应用程序来跟踪软件要求和与这些要求相关的测试。

最后一个组件的想法是,只要单击“浏览器”列表的必要条件,它就会被添加到当前测试的列表中。为了做到这一点,在与浏览器列表的@Output 事件关联的回调方法中,我尝试添加作为参数接收的Requisite :

addrequisite(requisite: Requisite) {
this.currentTest.requisites.push(requisite);
console.log('Current test: ');
console.log(this.currentTest);
}

TestView的 HTML 部分,我插入了RequisiteList组件,如下所示:

<app-requisitelist [requisites]="currentTest.requisites" ngModel name="reqlistview"></app-requisitelist>

ngModel属性是我一直在尝试的东西的一部分,我不确定它是否有必要)。

结果是:

我不确定我的问题是数据绑定是按值进行的(我不这么认为,因为我绑定了一个数组,它是一个对象 AFAIK),或者表没有检测到数据更改(我试过强制使用 ChangeDetector 进行数据更改检测)或其他任何东西。

标签: javascriptangulardata-bindingangular-material

解决方案


您将数组传递给app-requisitelist组件。此组件等待此数组更改以更新内容。当你这样做this.currentTest.requisites.push(requisite)时,数组this.currentTest.requisites不会改变,我的意思是,如果你这样做

const tmp = this.currentTest.requisites;
this.currentTest.requisites.push(requisite)
if (tmp === this.currentTest.requisites) {
    console.log('The arrays are the same');
}

您将打印日志。所以,我建议做这样的事情:

addrequisite(requisite: Requisite) {
    this.currentTest.requisites.push(requisite);
    this.currentTest.requisites = this.currentTest.requisites.map(item => item);
    console.log('Current test: ');
    console.log(this.currentTest);
}

插入的行强制this.currentTest.requisites成为具有相同内容的新数组。


推荐阅读