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
时。为什么是这样?
谢谢..
这是因为如果你使用push
将新项目添加到数组,那么数组引用不会更改,而纯管道只有在检测到输入值的纯变化时才会执行(在你的情况下为array
和value
)
有两种解决方案:
1)返回新数组
this.array = this.array.concat(4)
要么
this.array = [...this.array, 4];
2)使用不纯的管道
@Pipe({name: 'contains', pure: false})
export class ContainsPipe implements PipeTransform {
有关详细信息,请参阅