【问题标题】:Pass changing array to child component @Input field将更改数组传递给子组件@Input 字段
【发布时间】:2019-02-15 07:05:52
【问题描述】:

我正在尝试将数组传递给子组件。该数组是在父组件的 onInit 生命周期钩子的 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)
  }
}

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

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

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

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

    array: [] = [];
    

    【讨论】:

      【解决方案2】:

      我没有在您的子组件中看到 ngOnChanges。另外,请确保按照角度文档中指定的方式进行操作。 https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges

      【讨论】:

        猜你喜欢
        • 2018-05-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 1970-01-01
        • 2016-12-16
        • 1970-01-01
        • 2023-03-21
        相关资源
        最近更新 更多