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]; }
我更新了一些其他组件中的数组.虽然标签正确更新了数组的长度,但似乎没有更新复选框. contains只是一个简单的管道,用于检查value是否是数组的一部分.我在一个包含管道中放了一个console.log,当页面首先渲染时才得到输出,而不是在更改数组时.为什么是这样?
谢谢..
解决方法
那是因为如果使用push将新项添加到数组中,那么数组引用不会更改,而纯管只有在检测到输入值的纯变化时才会执行(在您的情况下为数组和值)
有两种解决方案:
1)返回新数组
this.array = this.array.concat(4)
要么
this.array = [...this.array,4];
2)使用不纯的管道
@Pipe({name: 'contains',pure: false}) export class ContainsPipe implements PipeTransform {
有关详细信息,请参阅
> 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