Data Transfer Between Sibling Components in Angular

47 Views Asked by At

I have two sibling components and a parent components. I want to transfer array data in child-two to child-one.

parent.component.html

<child-one (employees)="employeesFromChild"></child-one>
<child-two (outputFromChild)="getEmployees($event)"></child-two>

parent.component.ts

employeesFromChild!: Employee[];
getEmployees(event: Employee[]){
this.employeesFromChild = event;
}

child-one.component.ts

@Input() employees!: Employee[];
ngOnInit(){
 console.log(this.employees)
}

child-two.component.ts

selectedData: Employee[] = [
 {firstName: 'Max', lastName: 'Arnold', age: '25'},
 {firstName: 'Betty', lastName: 'Arnold', age: '22'},
 {firstName: 'Mark', lastName: 'Arnold', age: '20'},
];
@Output() outputFromChild: EventEmitter<Employee[]> = new EventEmitter<Employee[]>();
ngOnInit(){
this.outputFromChild.emit(this.selectedData);
}

I am getting undefined result in child-one when I console.log(this.employees). How can I fix it?

1

There are 1 best solutions below

0
Nikunj Parmar On

Use a square bracket instead of a round bracket in the child-one employees variable.

Square brackets are used for Input type event and Round brackets are used for output type event.

<child-one [employees]="employeesFromChild"></child-one>
<child-two (outputFromChild)="getEmployees($event)"></child-two>

And change child-one.component.ts life cycle hook to ngOnChanges instead of ngOnInit