-1

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?

  • the ngOnInit() of your parent component will be called first. Then the one of the child. It might work using ngAfterViewInit() in the parent and ngOnInit() in child-two. Furthermore I would suggest formatting your question, that makes it easier to answer it :) – user3691763 Aug 01 '23 at 07:59

1 Answers1

0

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

user776686
  • 7,933
  • 14
  • 71
  • 124