Home > database >  How to pass 2 parameters separately to the EventEmitter to pass them to function in Angular 2?
How to pass 2 parameters separately to the EventEmitter to pass them to function in Angular 2?

Time:03-04

I have a function that takes 2 parameters

students.component.ts

write(name : string, age : number) : void {
      ...
}

students.component.html

<app-student [student]="student" (write)="write(**?**)"></app-student>

how can I pass 2 variables from a child component?

student.component.ts

@Output() write = new EventEmitter();

writeStudentInfo(name : string, age : number) {
    this.write.emit(**?**);
}

CodePudding user response:

In this case, you'd either want two emitters, or change your code to be

@Output() write = new EventEmitter();

writeStudentInfo(name : string, age : number) {
    this.write.emit({ name, age });
}

and then your host component listener could be

onStudentInfo({name, age}) {
  // Do your thing here
}

CodePudding user response:

@JSmart523 already answered correctly.

Just for your codes, see below,

students.component.ts

write(name : string, age : number) : void {
  console.log(name, age);
}

students.component.html

<app-student [student]="student" (write)="write($event.name, $event.age)"></app-student>

student.component.ts

@Output() write = new EventEmitter();

writeStudentInfo(name : string, age : number) {
    this.write.emit({ name, age });
}
  • Related