aaron
aaron

Reputation: 267

How to pass multiple data back from child to parent component in angular?

Currently, I am using angular 4 for my school project. I have an array, each item is a child component which can be updated and deleted, which means I should know the index and the data.

parent.ts:

updOne(i:number,stc:string):void{
    this.myarray[i]=stc
}
delete(edu:string):void{
    this.myarray=this.myarray.filter(x=>x!==edu)
}

parent.html:

<child-com [edu]=x [num]=i (updstr)="updOne($event)" (delstr)="delete($event)"></child-com>

child-com.ts:

@Input() edu:string
@Input() num:number
@Output() updstr: EventEmitter<string> = new EventEmitter<string>()
@Output() delstr: EventEmitter<string> = new EventEmitter<string>()

//some other code here

save():void{
    this.updstr.emit(this.edu)
    this.updating=false
}
del():void{
    this.delstr.emit(this.edu)
}

delete works well, without a doubt. The problem is updating. Actually, using *ngFor, trackBy, and printing it all manually, this problem can be solved. But I wanna try using child component, as in React. When I play around with react, I can just use javascript closure, i.e. myfunc.bind(this,i,stc).

I've tried using bind here, no results

code when using bind:
parent.ts:

@Output() updstr: EventEmitter<number,string> = new EventEmitter<number,string>()

parent.html:

//I've tried some order
//this,i,$event
//$event,this,i
<child-com [edu]=x (updstr)="updOne.bind(this,$event,i)" (delstr)="delete($event)"></child-com>

And generics in typescript doesn't allow multiple data, so I cant emit more than one data

So my question is, how can I pass some data at once from child to parent, using emit or bind?

Upvotes: 0

Views: 6583

Answers (1)

aaron
aaron

Reputation: 267

Thanks to Alex, using an object can substitute multiple data passing. Just to make sure that the data is correct, an interface is used, kind of like this

export interface Interview{
    num:number
    payload:{
        dt:string
        seeker:string
    }
}

and used it like

@Output() updstr: EventEmitter<Interview> = new EventEmitter<Interview>()

Upvotes: 1

Related Questions