Angular 2 - 如何修改ngOnChange中的输入B(通过更改输入A触发)

时间:2017-02-17 11:54:12

标签: angular triggers onchange observable angular2-docheck

我有一个带有输入和变量的组件:

@Input() data: string[];
@Input() val: string = '';

ngOnChanges(changes: SimpleChanges) {
    for (let propName in changes) {
       if (propName == 'data') {
            this.val = 'hello';
       }
    }
}

问题是,当数据发生变化时,我需要更改输入 val 。但我有以下错误:

Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

谢谢!

1 个答案:

答案 0 :(得分:0)

创建setter更容易

_data: string[];
@Input() set data(val: string[]) {
  this._data = val;
  this.val = 'abc'
  // this.cdRef.detectChanges();
}
get data() { return this._data; }

@Input() val: string = '';

如果仍然出现错误,请添加

constructor(private cdRef:ChangeDetectorRef) {}

并在上面的setter中注释掉的行中注释。