【发布时间】: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