I am trying to @Input a list of objects; this results in the @Input variable being undefined.
What works: home.component.html:
<p>
<it-easy [mycount]="countItem" (result)="PrintResult($event)"></it-easy>
home works for {{countItem}}!
</p>
<p>
calculation result is: {{calcResult}}
</p>
And the code in home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'it-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent {
countItem: number;
calcResult: number;
constructor() {
this.countItem = 5;
this.calcResult = 0;
}
PrintResult($event) {
this.calcResult = +$event;
}
}
export class EasyComponent implements OnInit {
@Input('mycount') count = 0;
@Output('result') calculation = new EventEmitter<number>();
constructor() {
alert('count is ' + this.count);
}
So I made some adjustments to try sending a list of objects shown here from the same Home.component.html.
myNodesList: {title: string, count: number}[];
this.myNodesList = [
{title: "first", count: 1},
{title: "second", count: 2},
{title: "third", count: 3},
];
<p>
<it-hard [node]="myNodesList"></it-hard>
</p>
})
export class HardComponent implements OnInit {
@Input() node: {title: string, count: number}[];
constructor() {
const length = this.node.length;
}
And node is "undefined" .. in fact blows in the constructor at node.length.
Any thoughts? (without a fix, I'm going to have to run things through a service).
Thanks in advance.
TL;DR: Dont access
@Input
parameters in construcor. UsengOnInit
if you don't useasync
pipe and usengOnChanges
if you do useasync
pipe.You are trying to access
@Input
properties too early in Angulars component Lifecycle.Constructor
is not the lifecycle hook itself and its not a place to access@Input
parameters.Generally about hooks: https://angular.io/guide/lifecycle-hooks
As that page say:
You should wait at least for
ngOnInit()
and access it there although there are more considerations about it here: https://angular.io/guide/reactive-forms#when-to-set-form-model-values-ngonchangesNamely, even in
ngOnChanges
, although it fires first time beforengOnInit
, when usingaysnc
pipe you still might not have data inngOnInit
. So, as a safest and standard way, you should access your@Input
inngOnChanges
and inspect its parameters to filter those@Input
parameters that are of your interest at the moment.