2017-01-27 4 views
0

안녕하세요, 상위 구성 요소의 데이터를 하위 구성 요소 컨트롤러로 전달하는 데 약간의 문제가 있습니다.각도 2의 데이터를 하위 구성 요소로 전달

은 내가 값을 MyData 설정이 내 부모 구성 요소 parent.component.html

<element [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); 
    } 
} 

에서 @Input를 사용하여이 값을 설정?

+0

'Value'는 Ajax에서 채워 집니까? –

+0

아니,이 작품은 나를 위해' {{value}}'어떻게 생성자에서이 변수를 사용할 수 있습니까? – greenchapter

+0

왜 생성자 내부에서'value'를 얻고 싶습니까? 당신은 lifecycle event를 사용해야합니다 ... –

답변

1

당신은 (이 아직 초기화되지 것) 생성자에서 @Input 데이터에 액세스 할 수 없습니다, 당신이하는 OnInit 인터페이스를 구현해야합니다

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

export class My implements OnInit { 
    ... 

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

} 
+0

예이 작업을 완료했습니다 '@ angle/core'에서 가져 오기 {Component, OnInit, Input}, 각도는 ** Property 'mydata'가 없습니다 ' – greenchapter

+0

[여기] (https : // scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components) 문제를 이해하는 데 도움이됩니다. –

3

아마 비동기 문제, 당신이 JSON에서 데이터를 받고 보인다, 아마도 http 또는 뭔가를 통해 가져온 것입니다. undefined는 데이터가 실제로 검색되기 전에 해당 뷰가 렌더링되어 정의되지 않은 오류가 발생할 수 있기 때문에 발생했을 수 있습니다.

시도는 실제로 값이 될 때까지 아이 컴퍼넌트가 렌더링되지 않도록하는 조건을 설정합니다 :

<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); 
    } 
} 

희망이 있습니다.

관련 문제