2

Why input properties on component are not available in constructor

@Input() results: Result[];

constructor() {
   console.log(this.results); // why it is not available here 
}
alehn96
  • 1,363
  • 1
  • 13
  • 23
  • I think its set on the `ngOnChanges`-lifecycle hook. – robbannn Jun 12 '17 at 22:24
  • More info about the difference of constructor and OnInit to build upon answer of Jonnysai [difference between constructor and OnInit](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit) – AT82 Jun 13 '17 at 08:41

1 Answers1

10

Input property isn't initialized until view is set up so generally you can access input value on ngOnInit()

check LifeCycle. https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

import {Component, Input} from 'angular2/angular2'

@Component({
  selector: 'child',
  template: `   
    <p>The next number is {{ mynumber + 1 }}</p>
  `
})
class ChildComponent {
  @Input() mynumber: number;
    ngOnInit(){
         console.log(this.number);
   }
}

@Component({
  selector: 'parent',
  template: `
    <child [mynumber]="41"></child>
  `
})
export class ParentComponent {}
CharanRoot
  • 6,181
  • 2
  • 27
  • 45