动态更新Angular2中的[checked]

问题描述 投票:4回答:1

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时。为什么是这样?

谢谢..

angular angular2-template angular-pipe
1个回答
3
投票

这是因为如果你使用push将新项目添加到数组,那么数组引用不会更改,而纯管道只有在检测到输入值的纯变化时才会执行(在你的情况下为arrayvalue

有两种解决方案:

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

有关详细信息,请参阅

© www.soinside.com 2019 - 2024. All rights reserved.