I have a simple Angular 2 component with @Input, which I bind to the template. The template shows input data, but I cannot access it from the constructor:

import {Component, View, bootstrap, Input} from 'angular2/angular2';
import DataService from './data-service';

@Component({
    selector: 'app-cmp'
})
@View({
    template: `{{data.firstName}} {{data.lastName}}` //-> shows the correct 'data'
})
export default class NamesComponent {
  @Input() data: any;
  constructor(dataService: DataService) {
    console.log(this.data);//undefined
  }
}

Here is a plunker with an example (see "names-component.ts").

What am I doing wrong?

share|improve this question
    
ES6?​​​​​​​​​​​ – Cerbrus Nov 6 '15 at 7:49
    
This is written in Typescript – Yaniv Efraim Nov 6 '15 at 7:50
    
Right. Adding that tag. – Cerbrus Nov 6 '15 at 7:51
up vote 56 down vote accepted

Because the Input property isn't initialized until view is set up. According to the doc, you can access your data in ngOnInit method.

import {Component, bootstrap, Input, OnInit} from '@angular/core';
import DataService from './data-service';

@Component({
    selector: 'app-cmp',
    template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent implements OnInit {
  @Input() data;
  name: string;
  constructor(dataService: DataService) {
    this.name = dataService.concatNames("a", "b");
    console.log(this.data); // undefined here
  }
  ngOnInit() {
    console.log(this.data); // object here
  }
}
share|improve this answer
    
Thanks! This is exactly what I needed – Yaniv Efraim Nov 6 '15 at 8:42
4  
@YanivEfraim I have updated my answer, please check it out. And this api is likely to change in future. github.com/angular/angular/issues/5036 – Herrington Darkholme Nov 6 '15 at 9:15
1  
This answer is no longer relevant, however I can't edit the answer due to SO's far too aggressive limitations. You need to now use ngOnInit instead of onInit. – lux Dec 21 '15 at 20:38
1  
@lux I have updated – Herrington Darkholme Dec 23 '15 at 2:55
1  
updated for rc api. – Herrington Darkholme Jul 18 '16 at 2:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.