简体   繁体   English

角度2组件之间的接口传递数组

[英]Passing array of interfaces between components angular 2

i've got some troubles while passing data(Array) between components by @Input, there is some code. 我在通过@Input在组件之间传递数据(数组)时遇到了一些麻烦,有一些代码。 parent.component.ts: parent.component.ts:

public ngOnInit() {
    this.applications = new Array<ApplicationEntryInterface>();
(...)
let shortTermData = new ShortTermApplicationAdapter(application);
this.applications.push(shortTermData);
console.log(this.applications);
}

this console.log shows me normal array 此console.log向我显示正常数组 在此处输入图片说明 parent.component.html parent.component.html

<student-application-overview [applicationsEntry]="applications"></student-application-overview>

Child component: 子组件:

@Input('applicationsEntry') public applicationsEntry: Array<ApplicationEntryInterface>;
 ngOnChanges() {
console.log(this.applicationsEntry);
console.log(this.applicationsEntry.length); <--- shows 0
}

which shows 这表现了 在此处输入图片说明 It's impossible to iterate it in for, foreach, etc, only *ngFor works, this.applicationsEntry.length is equal to 0, how can I handle with it ? 不可能在for,foreach等中进行迭代,只有* ngFor可以使用,this.applicationsEntry.length等于0,我该如何处理呢? Also I used @Input (..) set (..) { (..) } and it gave same result 我也使用了@Input(..)set(..){(..)},它得到了相同的结果

I use ngOnChanges with changes . 我将ngOnChanges与changes一起使用。 This only will change if the current value is different from the previous value, but if your create an object every time it should work fine. 仅当当前值与先前的值不同时,这才会改变,但是如果您每次创建一个对象时都可以正常工作。

changes will record every item that is changed within the component. 更改将记录组件中更改的每个项目。

Try: 尝试:

ngOnChanges(changes: any) {
        if (changes.applicationsEntry) { // this help to filter out undefined
           console.log(changes.applicationsEntry.currentValue); // your current array should be here
        }
    }

我是Angular的新手,但是我总是使用此语法作为输入

@Input() applicationsEntry: Array<ApplicationEntryInterface>;

The problem resides in ChangeDetection of Angular, and the way you are "updating" the Array property on the parent component. 问题在于Angular的ChangeDetection ,以及您在父组件上“更新” Array属性的方式。

Just adding new items to an Array, child components are not noticed in the OnChanges lifecycle hook. 只是将新项目添加到Array, OnChanges生命周期挂钩中不会注意到子组件。

If you want to solve this common issue, on the parent component, do something similar to this: 如果要解决此常见问题,请在父组件上执行以下操作:

let shortTermData = new ShortTermApplicationAdapter(application);
this.applications.push(shortTermData);
this.applications = [...this.applications]; // Here is the "magic"

Last line creates a new deep-copy of the Array and allows the ChangeDetection of Angular to be noticed about the change in Arrays. 最后一行创建数组的新深层副本,并允许有关Arrays更改的角度通知Angular的ChangeDetection。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM