在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
的一部分.我将console.log
放在contains
管道中,并且仅在页面最初呈现时获得输出,而不是在更改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];
Plunker
2)使用不纯的管道
@Pipe({name: 'contains', pure: false})
export class ContainsPipe implements PipeTransform {
Plunker
有关更多详细信息,请参见
For more details see also
- NgFor doesn't update data with Pipe in Angular2
- Unraveling Angular 2 book, Chapter 1, Example 5
- https://angular.io/docs/ts/latest/guide/pipes.html
这篇关于在Angular2中动态更新[已检查]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!