Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access Inputs from my controller/constructor

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?

like image 253
Yaniv Efraim Avatar asked Nov 06 '15 07:11

Yaniv Efraim


Video Answer


2 Answers

Because the Input property isn't initialized until view is set up. According to the docs, 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   } } 
like image 112
Herrington Darkholme Avatar answered Sep 18 '22 15:09

Herrington Darkholme


You must implement OnChanges, see below:

import {Component, bootstrap, Input, OnChanges} from '@angular/core'; import DataService from './data-service';  @Component({     selector: 'app-cmp',     template: `{{data.firstName}} {{data.lastName}} {{name}}` }) export default class NamesComponent implements OnChanges {   @Input() data;   name: string;   constructor(dataService: DataService) {     this.name = dataService.concatNames("a", "b");     console.log(this.data); // undefined here   }   ngOnChanges() {     console.log(this.data); // object here   } } 
like image 22
André Rocha Avatar answered Sep 21 '22 15:09

André Rocha