2017-04-01 51 views
0

我想通過指令元標記從一個組件發送數據到另一個,但它顯示錯誤時,我不明白當我安慰它。任何人都可以請建議我help.Thanks。如何通過角度2中的指令標記發送值

我的組件,

import { ModalComponent } from './modal/modal.component'; 
@Component({ 
    selector: 'my-app', 
    template: `<modal [hero]="value"></modal>' 
}) 
export class CommonComponent { 
    value : anny ='1'; 

}

@Component({ 
    selector: 'modal', 
    templateUrl : './modal/model.component.html' 
}) 
export class CommonComponent { 
    @Input() hero:any; 
    consrtuctor(){ 
    console.log(this.hero) ///// shows o/p as undefined 

}

回答

0

看看lifecycle hooks

在Angular中,構造函數用於依賴注入。當您想要處理@Input()@Output()以及類似的修飾器時,您需要調用組件生命週期中的某個內置函數。

相反的constructor() {...},使用:

ngOnInit() { 
    console.log(this.hero); // not undefined 
} 
0

你面臨的問題是,在您的構造函數被調用來看,@input和@Output綁定沒有被角設立尚未。這就是爲什麼你的英雄屬性顯示爲未定義。如果要在組件的初始化期間使用@Input和/或@Output綁定,則必須等到Angular嘗試使用它們之前初始化這些綁定。

Angular提供了一個生命週期鉤子來完成這件事情。基本上,如果您在組件上定義了一個名爲ngOnInit的方法,那麼在Angular完成初始化組件後,它將調用該方法。在這一點上,你的綁定將具有你期望的價值。

所以,你的類應該更像:

export class CommonComponent { 
    @Input() hero:any; 
    constructor(){ } 

    ngOnInit() { 
    console.log(this.hero) // will be defined at this point 
    } 
} 

在一般情況下,你真的不應該有任何真正的初始化邏輯在構造函數(因爲再次,在點你的構造函數被調用,沒有你綁定到位)。對於絕大多數組件,您的構造函數僅用於通過將這些服務列爲構造函數的參數來請求服務依賴項 - 組件的初始化發生在ngOnInit中。

查看lifecycle hooks guide瞭解更多。