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

查看:22
本文介绍了在 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 向数组添加新项,那么在执行纯管道时,数组引用不会改变仅当它检测到对输入值的纯粹更改(在您的情况下为 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

更多详情请见

这篇关于在 Angular2 中动态更新 [已检查]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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