How to pass data modal Component to parent Component using ng-bootstrap in angular 4

喜你入骨 提交于 2020-04-10 18:42:30

问题


I tried below coding for pass data from modal component to parent component.

package.json

"@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.3"

app.component.html

<button class="btn btn-primary" (click)="openModal()">Open</button>

app.component.ts

import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

export class AppComponent {

   constructor(private modalService: NgbModal) { }

    openModal() {
        const modalRef = this.modalService.open(AppModalComponent);
    }
}

app-modal.component.html

<h1>{{data}}</h1>
<button class="btn btn-primary" (click)="addMe()"></button>

app-modal.component.ts

import { Component, Output, EventEmitter } from '@angular/core';

export class AppModalComponent {
    private data: string;
    @Output emitService = new EventEmitter();

    constructor() {
        this.data = "hello world";
    }

    addMe() {
        this.emitService.next(this.data)
    }
}

After emit, how to get data in parent Component (app.component) ??


回答1:


You could subscribe to the emitService @Output like so:

openModal() {
     const modalRef = this.modalService.open(AppModalComponent);
     modalRef.componentInstance.emitService.subscribe((emmitedValue) => {
         // do sth with emmitedValue
     });
}

While the above will work, please note that it is usually easier to just close modal with the value you want to return. This will resolve a promise available on the modalRef. More details in https://stackoverflow.com/a/43614501/1418796



来源:https://stackoverflow.com/questions/46075862/how-to-pass-data-modal-component-to-parent-component-using-ng-bootstrap-in-angul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!