Cannot access Inputs from my controller/constructor

AngularTypescript

Angular Problem Overview


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?

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

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

Solution 3 - Angular

The way to access your data per documentation here is to write a setter and a getter. Inside those methods you can manipulate your object/data. Look here:

  private _data = '';

  @Input()
  set data(data: any) {
    this._data = data;
  }

  get data(): string { 
    console.log(_data) // <-------- you will see your data here
    return this._data; 
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYaniv EfraimView Question on Stackoverflow
Solution 1 - AngularHerrington DarkholmeView Answer on Stackoverflow
Solution 2 - AngularAndré RochaView Answer on Stackoverflow
Solution 3 - AngularGelView Answer on Stackoverflow