在Angular2中动态更新[已检查] [英] Dynamically updating [checked] in Angular2

查看:99
本文介绍了在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向数组添加新项,则数组引用不会更改,而纯管道仅在检测到纯更改输入值(在您的情况下为arrayvalue)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆