简体   繁体   中英

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. 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 在此处输入图片说明 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 ? Also I used @Input (..) set (..) { (..) } and it gave same result

I use ngOnChanges with 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.

Just adding new items to an Array, child components are not noticed in the OnChanges lifecycle hook.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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