提问人:Ezgi Ozdemir 提问时间:8/1/2023 更新时间:8/5/2023 访问量:35
Angular 中同级组件之间的数据传输
Data Transfer Between Sibling Components in Angular
问:
我有两个同级组件和一个父组件。我想将子 2 中的数组数据传输到子 1。
父.组件.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);
}
当我控制台.log(this.employees)时,我在子一中得到未定义的结果。我该如何解决?
答:
0赞
Nikunj Parmar
8/1/2023
#1
在 child-one employees 变量中使用方括号而不是圆括号。
方括号用于输入类型事件,圆括号用于输出类型事件。
<child-one [employees]="employeesFromChild"></child-one>
<child-two (outputFromChild)="getEmployees($event)"></child-two>
并将child-one.component.ts生命周期挂钩更改为 ngOnChanges 而不是 ngOnInit
评论