我创建了两个组件,并将其命名为父级和子级。我将这些组件链接到app.component.html。 现在我在子组件中有一个对象数组,我的目标是使用@Output显示父组件中的那些对象数组。 我的预期输出是每个对象都应该在单独的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
这是childcomponent.html
<div class="childclass">
<h1>This is Child</h1>
</div>
这是childcomponent.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() {
}
}
这是parentcomponent.html
<div class='parentclass'>
<h1>This is Parent</h1>
</div>
这是parentcomponent.css
.parentclass {
background-color: aqua;
}
此parentcomponent.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() {
}
}
答案 0 :(得分:0)
使用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
}
parent.component.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);
}
答案 1 :(得分:0)
我的目标是通过使用@Output
来显示父组件中的那些对象数组
最好将服务与 @Output 一起使用,因为parent component
和child component
是彼此的兄弟姐妹。
Service.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
对象中,完成后,在EventEmitter的帮助下调用Parent类(这里是AppComponent)。employeeData
对象以检索父组件中的数据。看看这里了解有关data sharing between sibling components in Angular
希望这对您有帮助。.:)