Angular EventEmitter&输出到打开模态

时间:2018-03-12 21:25:12

标签: angular

我知道,一旦父/子小孩/家长通讯为我点击,我的生活便会变得如此简单。与此同时,这是我试图完成的事情。

在我的模块中,我有两个子组件。该表有一个发出事件的按钮(在本例中是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参数传递给它。

显然这不起作用,否则我不会在这里发帖。我错过了什么?

1 个答案:

答案 0 :(得分:1)

在主要组件模板集中,从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);
}
...