Angular 2/4 @Input only moves intrinsics - not lis

2019-02-20 02:18发布

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;
  }
}
It-Easy gets the inputs (and outputs) like this:

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},
];
Home.html now looks like:

<p>
  <it-hard [node]="myNodesList"></it-hard>
</p>
Now the part that FAILS: it-hard.component.ts

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

1条回答
Emotional °昔
2楼-- · 2019-02-20 03:12

TL;DR: Dont access @Input parameters in construcor. Use ngOnInit if you don't use async pipe and use ngOnChanges if you do use async 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:

The constructor isn't an Angular hook per se. The log confirms that input properties (the name property in this case) have no assigned values at construction.

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

Namely, even in ngOnChanges, although it fires first time before ngOnInit, when using aysnc pipe you still might not have data in ngOnInit. So, as a safest and standard way, you should access your @Input in ngOnChanges and inspect its parameters to filter those @Input parameters that are of your interest at the moment.

查看更多
登录 后发表回答