Dynamically updating [checked] in Angular2

最后都变了- 提交于 2019-12-01 19:04:27

问题


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];
}

I update array in some other components. While the label updates the array's length correctly, the check box doesn't seem to be updated. contains is just a simple pipe that checks if value is part of array. I put a console.log in the contains pipe and only got the output when the page renders at first, not when array is changed. Why is this?

Thanks..


回答1:


That's because if you use push to add new item to array then the array reference isn't changed while pure pipe will be executed only when it detects a pure change to the input value (array and value in your case)

There is two solutions:

1) return new array

this.array = this.array.concat(4)

or

this.array = [...this.array, 4];

Plunker

2) use impure pipe

@Pipe({name: 'contains', pure: false})
export class ContainsPipe implements PipeTransform {

Plunker

For more details see also

  • 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


来源:https://stackoverflow.com/questions/39941185/dynamically-updating-checked-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!