Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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 44 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 onInit method.

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

@Component({
    selector: 'app-cmp',
    template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent {
  @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
    
Based on the newer api, you actually need to import OnInit from "angular2/angular2", and then change your class to implement OnInit so it should look like: export default class NamesComponent implements OnInit { ... } – jgo Dec 4 '15 at 22:37
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

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.