2017-02-16 32 views
1

我需要將一些數據轉移到子元素並在其中運行函數。 我使用ViewChild來訪問該功能。但在孩子childParam仍未定義。Angular2。我可以同時使用ViewChild和@Input嗎?

父模板:

<my-modal #myModal [childParam]="parentParam"></my-modal> 

父組件:

@ViewChild('myModal') myModal; 
parentParam: any; 

onSubmit(value: any){ 
    this.parentParam = value; 
    this.myModal.modalShow(); 
} 

子組件:

@Input() childParam: any; 

modalShow(){ 
    console.log(this.childParam); 
} 

爲什麼childParam是不確定的?

更好的是:改變直接childParam通過ViewChild

this.myModal.childParam = 'test string'; 

或發送數據,通過功能參數:

this.myModal.modalShow('test string'); 
+0

我想'parentParam'尚未設置時'modalShow()'被調用,但很難說,因爲代碼不允許派生出可能會發生的事情。 –

+0

我創建了plunker [鏈接](https://plnkr.co/edit/ZcZaJ0Wbu9CAobxkd2LJ?p=preview)。當我第一次點擊按鈕 - 沒有顯示任何內容時,第二次點擊 - 顯示字符串。 – MikeS

回答

0

this.parentParam = value;onSubmit()然後角首先需要執行運行變化檢測綁定得到更新。

當事件處理程序完成時,角度運行會更改檢測。在你的情況是onSubmit()這意味着childParam將得到value通過之後onSubmit()被執行。

你可以做的是運行變化檢測明確地

constructor(private cdRef:ChangeDetectorRef) {} 

    onSubmit(value: any){ 
    this.parentParam = value; 
    this.cdRef.detectChanges(); 
    // here `value` is assigned to `childParam` 
    this.myModal.modalShow(); 
    } 

Plunker example

0

你並不需要通過@ViewChild基準來設定參數孩子。

試試這個。父模板:

<my-modal #myModal [childParam]="parentParam"></my-modal> 

父組件:

private parentParam: any; 

onSubmit(value: any){ 
    this.parentParam = value; 
    this.myModal.modalShow(); 
} 

parentParam的值將綁定到childParam值直接以這種方式使每當parentParam值更新它會在子組件可用。

如果不工作,那麼嘗試添加ngOnChanges到子組件,因爲你會再能調試(設置斷點)每當值從父更新:

進口OnChanges(添加此除了等進口從@角/核心)有:

import { OnChanges} from '@angular/core'; 

添加NgOnChanges你的孩子組件類:

export class MyChildComponent implements OnChanges { 

Implemen t方法ngOnChanges。每當輸入參數發生變化,該方法將被調用:

ngOnChanges(changes: any) { 
    debugger; //set breakpoint 
} 
相關問題