动态更新Angular2中的[checked]

时间:2016-10-09 07:39:54

标签: angular angular2-template angular-pipe

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只是一个简单的管道,用于检查valuearray的一部分。我在console.log管道中放了一个contains,并且只在页面首先渲染时获得输出,而不是在array更改时。这是为什么?

谢谢..

1 个答案:

答案 0 :(得分: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

有关详细信息,请参阅