[英]How to pass Array of Objects from Child Component to Parent Component in angular
我創建了兩個組件並將其命名為父子組件。 我在 app.component.html 鏈接了這些組件。 現在我在子組件中有一個對象數組,我的目標是使用@Output 在父組件中顯示這些對象數組。 我預期的 output 是每個 object 應該在一個單獨的 div 中。
如果我不清楚我的疑問,請發表評論。
這是 app.component.html
<div class="container">
<div class="row">
<div class="col-6">
<app-parent></app-parent>
</div>
<div class="col-6">
<app-child></app-child>
</div>
</div>
</div>
這是 app.component.css
There is no css in this
這是子組件。html
<div class="childclass">
<h1>This is Child</h1>
</div>
這是子組件。css
.childclass {
background-color: burlywood;
}
這是 childcomponent.ts
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
employs = [
{
name: `Mark`,
age: 27,
jobProfile: 'React Developer'
},
{
name: 'Williams',
age: 29,
jobProfile: 'Angular Developer'
},
{
name: 'Tom',
age: 32,
jobProfile: 'Vuejs Developer'
}
]
@Output()
outputFromChild: EventEmitter<any> = new EventEmitter<any>()
constructor() { }
ngOnInit() {
}
}
這是父組件。html
<div class='parentclass'>
<h1>This is Parent</h1>
</div>
這是父組件。css
.parentclass {
background-color: aqua;
}
這個父組件.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
使用EventEmitter
以便您應該能夠從孩子到父母進行交流。
app.component.html
<div class="container">
<div class="row">
<div class="col-6">
<app-parent [employees]="employeesFromChild"></app-parent>
</div>
<div class="col-6">
<app-child (ouputFromChild)="getEmployees($event)"></app-child>
</div>
</div>
</div>
app.component.ts
employeesFromChild: any;
getEmployees(event){
this.employeesFromChild = event; //here you will get the employees from child
}
父組件.ts
@Input() employees: any;
ngOnInit(){
console.log(this.employees);
}
child.component.ts
employs = [
{
name: `Mark`,
age: 27,
jobProfile: 'React Developer'
},
{
name: 'Williams',
age: 29,
jobProfile: 'Angular Developer'
},
{
name: 'Tom',
age: 32,
jobProfile: 'Vuejs Developer'
}
]
@Output()
outputFromChild: EventEmitter<any> = new EventEmitter<any>()
ngOnInit() {
this.ouputFromChild.emit(employs);
}
我的目標是使用 @Output 在父組件中顯示這些對象數組
最好將服務與@Output一起使用,因為parent component
和child component
是彼此的兄弟。
服務.ts
export class ServiceName {
private employeeData= new BehaviorSubject<any>();
getEvent(): Observable<any> {
return this.employeeData.asObservable();
}
setEvent(param: any): void {
this.employeeData.next(param);
}
}
您需要遵循幾個步驟來完成您的要求,
employeeData
object 中,一旦完成,在 EventEmitter 的幫助下調用 Parent class(這里是 AppComponent)。employeeData
object 以檢索父組件中的數據。 在這里查看以了解有關data sharing between sibling components in Angular
更多信息
希望這對你有幫助.. :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.