我正在尝试将数组传递给子组件。该数组是在父组件的 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/