我知道,一旦我的 parent / child 之间的沟通顺利,我的生活就会变得更加轻松。与此同时,这就是我试图实现的目标。
在我的模块中,我有两个子组件。该表有一个发出事件的按钮(在本例中为 userId)以及应该监听该事件的模式。
因此,从表组件开始,我有一个方法来获取已单击的 userId:
editUser(id) {
this.userId.emit(id);
}
<button class="btn btn-transparent py-0"
tooltip="Edit User"
container="body"
(click)="editUser(row.userId)">
<small><span class="fa fa-pencil text-secondary"></span></small>
</button>
然后在我的模态组件中,我有另一个方法,应该将 userId 传递给它。
openModal(id?) {
console.log(id);
this.modalService.open(this.content);
}
然后在我的主组件模板中我设置监听事件
<header class="bg-white">
<h4 class="text-primary my-0">{{ 'USERS.HEADING' | translate }}</h4>
<div class="inner">
<app-double-pitch-button></app-double-pitch-button>
</div>
<div class="utility">
<div class="input-search">
<input class="form-control" [(ngModel)]="searchText" type="text" placeholder="{{ 'COMMON.SEARCH' | translate }}">
</div>
<button class="btn btn-primary btn-rounded ml-5"
(click)="firmModal.openModal()">
{{ 'USERS.NEW_USER' | translate }}
</button>
</div>
</header>
<app-firm-table class="py-2 px-3" [searchText]="searchText"></app-firm-table>
<app-firm-modal #firmModal (openModal)="firmModal.openModal($event)"></app-firm-modal>
它应该触发 openModal()
方法并将 id 参数传递给它。
很明显这不起作用,否则我不会在这里发帖。我错过了什么?
最佳答案
在主组件模板中设置监听 app-firm-table 中的事件(userId)并将发送事件设置为 app-firm-modal。
<app-firm-table class="py-2 px-3" (userId)="openModalInMainComponent($event)" [searchText]="searchText"></app-firm-table>
<app-firm-modal #firmModal [openModal]="openModalEvent"></app-firm-modal>
在主组件ts文件中添加:
public openModalEvent: EventEmitter<number> = new EventEmitter<number>();
openModalInMainComponent(id): void {
this.openModalEvent.emit(id);
}
在模态组件中添加:
@Input() openModal: EventEmitter<number>;
private openModalSubscribe: Subscription;
ngOnInit() {
....
this.openModalSubscribe = this.openModal.subscribe(event => {
this.openModal(event);
})
}
ngOnDestroy() {
...
this.openModalSubscribe.unsubscribe();
}
在表格组件中,它应该如下所示:
@Output() userId: EventEmitter<number> = new EventEmitter<number>();
editUser(id) {
this.userId.emit(id);
}
...
关于Angular EventEmitter 和输出以打开模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244639/