javascript - 材料表未反映数据源的更改
问题描述
这是我在 Stack Overflow 上的第一个问题。我会尽量具体,但我不知道如何保持简短,所以这将是一个很长的帖子。对于那个很抱歉。我保证我在问之前搜索并尝试了很多东西,但我现在有点迷路了。
我正在 Angular 6 中开发一个简单的应用程序来跟踪软件要求和与这些要求相关的测试。
我有一个名为RequisiteList的组件,它的 HTML 部分包含在一个 mat-table 中,其中包含我自己的Requisite模型类的数组作为 [dataSource]。这个数组作为@Input 参数接收,它还有一个@Output 参数,它是一个EventEmitter,每次单击列表上的Requisite时都会通知并传递给父组件。
我在ReqListMain中使用RequisiteList,它是一个由列表和用于过滤的分层树组成的组件。该组件工作正常,按预期显示和过滤必需品。该组件还捕获列表的@Output 事件并将其作为@Output 传递给其父级。
最后(关于它与这个问题的关系),我有一个TestView组件,它有一个RequisiteList实例来显示当前与当前测试关联的先决条件,以及一个ReqListMain实例来向当前测试添加新的先决条件(如“浏览器”)。这个TestView有一个模型类Pectest的实例,对应于当前正在可视化的测试,它有一个Requisite数组。
最后一个组件的想法是,只要单击“浏览器”列表的必要条件,它就会被添加到当前测试的列表中。为了做到这一点,在与浏览器列表的@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属性是我一直在尝试的东西的一部分,我不确定它是否有必要)。
结果是:
- 单击的必备项未显示在列表中。
- 在控制台输出中,我可以看到currentTest对象的内容,并且我验证单击的必备项实际上已添加到该对象的必备项数组中,因此事件触发并且对象由子组件向上传递。
我不确定我的问题是数据绑定是按值进行的(我不这么认为,因为我绑定了一个数组,它是一个对象 AFAIK),或者表没有检测到数据更改(我试过强制使用 ChangeDetector 进行数据更改检测)或其他任何东西。
解决方案
您将数组传递给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
成为具有相同内容的新数组。
推荐阅读
- tensorboard - 如何用张量板批量写入?
- python - Python bdist_wheel + install 有效,但由于 PEP 517 sdist + install 失败
- java - 删除Horizontal RecyclerView java中项目之间的空格
- css - Bootstrap 如何导入我的自定义变量而不是可怕地增加编译时间?
- javascript - 为什么动画回调会扰乱我组件的生命周期?
- arrays - 用 C 语言反转句子,单词之间只有一个空格字符
- python - Pyyaml 条件语句
- encryption - 0.9.8h 和 1.1.1k 之间的 Openssl 兼容性问题
- python - Python框架pypi包安装问题
- node.js - 无法访问嵌套集合 Firestore