Cannot access Inputs from my controller/constructor
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
}
}
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
}
}