2017-02-21 54 views
0

我試圖在另一個父組件中實現一個錯誤消息組件。在孩子(錯誤信息)組件中,它有一個輸入屬性,父組件將把錯誤信息傳遞給子節點。我似乎無法一直監聽輸入字段的子組件,因爲子組件只能呈現一次。任何人都可以給我一些見解,我如何解決這個問題?Angular2:子組件如何始終監聽來自父組件的輸入onInit

輔元件

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'; 
    } 
} 
+0

您可以將'errorType'設置爲setter。 –

回答

2

你可以在子組件使用OnChanges

ngOnChanges() { 
    console.log(this.errorType); 
} 

應該捕捉父母做errorType每一個變化。

ngOnChangesngOnInit之前被調用,並且每當有一個或多個數據綁定輸入屬性發生變化時。

相關問題