Actually, there are two ways of detecting and acting up on when an input changes in the child component in angular2+ :
您可以使用旧答案中提到的 ngOnChanges() lifecycle method :
@Input() categoryId: string;
ngOnChanges(changes: SimpleChanges) {
this.doSomething(changes.categoryId.currentValue);
// You can also use categoryId.previousValue and
// categoryId.firstChange for comparing old and new values
}
或者,您也可以使用 input property setter ,如下所示:
private _categoryId: string;
@Input() set categoryId(value: string) {
this._categoryId = value;
this.doSomething(this._categoryId);
}
get categoryId(): string {
return this._categoryId;
}
文档链接:看here .
WHICH APPROACH SHOULD YOU USE?
如果您的组件有多个输入,那么,如果您使用ngOnChanges(),