![](/img/trans.png)
[英]Angular2: How to reset input property after it is changed from child component programatically but not changed in parent binding?
[英]Angular2: How can a child component consistently listen to an input from the parent component after onInit
我正在嘗試在另一個父組件中實現錯誤消息組件。 在子(錯誤消息)組件中,它具有輸入屬性,父組件會將錯誤消息傳遞給子cmp。 我似乎無法讓子組件持續監聽輸入字段,因為子組件僅渲染一次。 誰能給我一些有關如何解決此問題的見解?
子組件
export class ErrorMessage implements OnInit {
@Input() errorType: string;
errorMessage;
messages = {
apiError: 'There is an error with your request. Please try again.',
}
ngOnInit() {
this.errorMessage = this.messages[this.errorType];
}
}
父組件
@Component({
selector: 'parent-component',
template: '<error-message *ngIf="errorType" [errorType]="errorType"></error-message>'
})
export class ParentComponent implements OnInit {
errorType: string;
throwingErrorFn(){
this.errorType = 'apiError';
}
}
您可以在子組件中使用OnChanges
:
ngOnChanges() {
console.log(this.errorType);
}
它應該捕獲對errorType
中的errorType
所做的每個更改。
ngOnChanges
在ngOnInit
之前以及每當一個或多個數據綁定輸入屬性更改時調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.