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
更改时。这是为什么?
谢谢..
答案 0 :(得分:3)
那是因为如果你使用push
向数组添加新项目,那么数组引用不会被更改,而纯管道只有在检测到输入值的纯粹更改时才会被执行(在您的情况下为array
和value
)
有两种解决方案:
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 强>
有关详细信息,请参阅