2

Hello I have a little problem passing data from a parent Component to a child component controller.

Thats the markup code of my parent Component parent.component.html

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

With this I set mydata with an value.

I set this value using @Input in my child controller

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

I get an undefined in the console, but why?

4
  • does Value gets populated from Ajax? Commented Jan 27, 2017 at 10:29
  • No, this works for me <element [mydata]="value">{{value}}</element> but how can I use this variable in the constructor? Commented Jan 27, 2017 at 10:43
  • why you want to get value inside constructor.. you should use lifecycle event... Commented Jan 27, 2017 at 10:45
  • At the moment I load an JSON from the constructre and I need an different jsonfilename. So I will pass the filename trough the component. Commented Jan 27, 2017 at 10:50

1 Answer 1

4

Probably a async problem, as it seems you are getting the data from json, which is probably fetched via http or something. The undefined is probably caused by that view is rendered before the data actually has been retrieved, which would throw an undefined error.

Try to set a condition, that the child component won't be rendered until it actually has a value:

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

And keep the current setup that you have been suggested from other answer, i.e:

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

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.