我有两个兄弟组件和一个父组件。我想将子二中的数组数据传输到子一中。
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);
}
当我 console.log(this.employees) 时,我在子一中得到未定义的结果。我该如何解决它?
在 child-one 员工变量中使用方括号而不是圆括号。
方括号用于Input类型事件,圆括号用于output类型事件。
<child-one [employees]="employeesFromChild"></child-one>
<child-two (outputFromChild)="getEmployees($event)"></child-two>
并将 child-one.component.ts 生命周期挂钩更改为 ngOnChanges 而不是 ngOnInit