【问题标题】:Angular 2/4 @Input only moves intrinsics - not lists or objectsAngular 2/4 @Input 只移动内在函数——而不是列表或对象
【发布时间】:2017-12-15 19:27:52
【问题描述】:

我正在尝试@Input 对象列表;这会导致 @Input 变量未定义。

什么有效: home.component.html:

<p>
  <it-easy [mycount]="countItem" (result)="PrintResult($event)"></it-easy>
  home works for {{countItem}}!
</p>
<p>
  calculation result is: {{calcResult}}
</p>

还有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 像这样获取输入(和输出):

export class EasyComponent implements OnInit {
  @Input('mycount') count = 0;
  @Output('result') calculation = new EventEmitter<number>();
  constructor() {
    alert('count is ' + this.count);
  }

所以我做了一些调整,尝试从同一个 Home.component.html 发送此处显示的对象列表。

myNodesList: {title: string, count: number}[];
this.myNodesList = [
  {title: "first", count: 1},
  {title: "second", count: 2},
  {title: "third", count: 3},
];
Home.html 现在看起来像:

<p>
  <it-hard [node]="myNodesList"></it-hard>
</p>
现在失败的部分:it-hard.component.ts

})
export class HardComponent implements OnInit {
  @Input() node: {title: string, count: number}[];
  constructor() {
    const length = this.node.length;
  }

并且节点是“未定义的”.. 实际上在 node.length 处的构造函数中吹了。

有什么想法吗? (如果没有修复,我将不得不通过服务运行)。

提前致谢。

【问题讨论】:

    标签: javascript html angular input


    【解决方案1】:

    TL;DR: 不要访问构造函数中的@Input 参数。如果您不使用async 管道,请使用ngOnInit;如果您使用async 管道,请使用ngOnChanges


    您试图在 Angulars 组件生命周期中过早访问 @Input 属性。 Constructor 不是生命周期钩子本身,也不是访问 @Input 参数的地方。

    通常关于钩子: https://angular.io/guide/lifecycle-hooks

    正如该页面所说:

    构造函数本身并不是一个 Angular 钩子。日志确认输入属性(在本例中为 name 属性)在构造时没有分配值。

    您应该至少等待ngOnInit() 并在那里访问它,尽管这里有更多关于它的注意事项: https://angular.io/guide/reactive-forms#when-to-set-form-model-values-ngonchanges

    也就是说,即使在ngOnChanges 中,虽然它在ngOnInit 之前第一次触发,但在使用aysnc 管道时,您仍然可能在ngOnInit 中没有数据。因此,作为最安全和标准的方式,您应该在ngOnChanges 中访问您的@Input 并检查其参数以过滤您目前感兴趣的@Input 参数。

    【讨论】:

    • 优秀。我相信毫无疑问你是对的。这给了我前进所需的一切。非常感谢。 (上升)
    猜你喜欢
    • 2017-11-08
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    • 2017-02-22
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多