在 Angular2 中动态更新 [已检查] [英] Dynamically updating [checked] in Angular2
问题描述
componentA.ts:
@Input() array;
<input type="checkbox" [checked]="array | contains: value"/>
<label>{{array.length}}</label>
componentB.ts:
@Component({
selector: 'app-component-b',
templateUrl: './app.component-b.html'
})
export class AppComponentB {
array = [1, 2, 3];
}
我更新了一些其他组件中的 array
.虽然 label
正确更新了数组的长度,但复选框似乎没有更新.contains
只是一个简单的管道,用于检查 value
是否是 array
的一部分.我在 contains
管道中放了一个 console.log
并且只在页面最初呈现时得到输出,而不是在 array
改变时.这是为什么?
I update array
in some other components. While the label
updates the array's length correctly, the check box doesn't seem to be updated. contains
is just a simple pipe that checks if value
is part of array
. I put a console.log
in the contains
pipe and only got the output when the page renders at first, not when array
is changed. Why is this?
谢谢..
推荐答案
那是因为如果你使用 push
向数组添加新项,那么在执行纯管道时,数组引用不会改变仅当它检测到对输入值的纯粹更改(在您的情况下为 array
和 value
)
That's because if you use push
to add new item to array then the array reference isn't changed while pure pipe will be executed only when it detects a pure change to the input value (array
and value
in your case)
有两种解决方案:
1) 返回新数组
this.array = this.array.concat(4)
或
this.array = [...this.array, 4];
2) 使用不纯的管道
@Pipe({name: 'contains', pure: false})
export class ContainsPipe implements PipeTransform {
更多详情请见
- NgFor 不会在 Angular2 中使用 Pipe 更新数据
- 解读 Angular 2 书籍,第 1 章,示例 5
- https://angular.io/docs/ts/latest/guide/pipes.html
这篇关于在 Angular2 中动态更新 [已检查]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!