2

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

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

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

问题是,我需要在数据更改时更改输入值。但我有以下错误:

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

谢谢 !

4

1 回答 1

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) {}

并在上面的设置器中注释掉的行中进行注释。

于 2017-02-17T12:57:21.400 回答