javascript - 将更改数组传递给子组件@Input 字段

标签 javascript angular

我正在尝试将数组传递给子组件。该数组是在父组件的 onInit 生命周期 Hook 的 subscribe 方法中定义的。

父组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'selector-parent',
  templateUrl: 'parent.component.html'
})

export class ParentComponent implements OnInit {

  array: [];

  constructor() { }

  ngOnInit() {
    this.appDataService.getValues()
      .subscribe(
        value => {
          value.item
            .filter(loaded => !this.array.some(existing => existing.key === loaded.key))
            .forEach(loaded => { this.array.push(loaded) })
        }
      )
  }
}

子组件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '[selector-child]',
  templateUrl: 'child.component.html'
})

export class ChildComponent implements OnInit {

  @Input() inputArray: [];

  constructor() { }

  ngOnInit() {
    console.log(this.inputArray)
  }
}

绑定(bind)是:<tr selector-child [inputArray]="array"></tr>

不幸的是,inputArray 上的控制台日志显示为未定义。我尝试在子组件中使用 ngOnChanges 但由于某种原因,它无法识别父组件中的更改。如果没有更简单的方法来解决问题,请考虑使用服务来传递数据。

最佳答案

您必须在父组件中初始化数组:

array: [] = [];

关于javascript - 将更改数组传递给子组件@Input 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52264695/

相关文章:

angular - 如何在 Angular 7 中设置超时 KeyUp

javascript - createPattern 未按预期返回

javascript - 通过 AJAX 加载 SPA 网页

php - 通过 PHP (CodeIgniter) 从数据库中使用 JQuery 自动完成

javascript - 错误 : The ChromeDriver could not be found

javascript - Angular2 将 html 传递给组件

javascript - Jwplayer 6.11 不显示 Controller 按钮

javascript - 我可以动态渲染 NgModal 的 HTML吗

javascript - 将 SVG 元素的宽度和高度设置为 100% 对我们有什么好处吗?

angular - 可观察值是另一个可观察值的一部分