2017-01-27 59 views
0

你好我有一個小問題,從一個父組件傳遞數據到一個子組件控制器。將Angular2中的數據傳遞給子組件

這就是我的父Component parent.component.html

<element [mydata]="Value"></element> 

的標記代碼有了這個,我設置MYDATA與價值。

我設置我的孩子控制器

import { Component, OnInit, Input } from '@angular/core'; 

@Component({ 
    selector: 'element', 
    templateUrl: './element.component.html', 
    styleUrls: ['./element.component.scss'], 
}) 

export class ElementComponent implements OnInit { 

    @Input() public mydata:string; 

    ngOnInit() { 
     console.log(this.mydata); 
    } 
} 

使用@input這個值,我得到一個未定義的控制檯,但是爲什麼呢?

+0

'價值'從Ajax填充? –

+0

不,這適用於我''元素[mydata] =「值」> {{價值}}​​'但我怎麼能在構造函數中使用這個變量? – greenchapter

+0

爲什麼你想要在構造函數中獲得'value' ..你應該使用生命週期事件... –

回答

1

無法訪問構造@Input數據(它尚未初始化),您需要實現OnInit的接口:

import { OnInit } from "@angular/core"; 

export class My implements OnInit { 
    ... 

    ngOnInit() { 
     console.log(this.mydata); 
    } 

} 
+0

是的,我也做這個 '進口{組件,OnInit中,輸入}從 '@角/芯';' 但角度說**房產 'MYDATA' 不存在 – greenchapter

+0

[這裏](https://開頭scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components)將有助於理解問題 –

3

可能是一個異步的問題,因爲它似乎你是從JSON獲取數據,這可能是通過http或其他東西獲取的。未定義可能是由於該視圖在數據實際被檢索之前呈現,這會導致未定義的錯誤。

嘗試設置的條件,使孩子組件將不會被渲染,直到它實際上有一個值:

<element *ngIf="value" [mydata]="value"></element> 

,對您已經從其他的答案提出的當前設置,即:

import { Component, OnInit, Input } from '@angular/core'; 

@Component({ 
    selector: 'element', 
    templateUrl: './element.component.html', 
    styleUrls: ['./element.component.scss'], 
}) 


export class ElementComponent implements OnInit { 

@Input() public mydata:string; 

    ngOnInit() { 
    console.log(this.mydata); 
    } 
} 

希望這有助於!

相關問題