如何使用角度4中的ng-bootstrap将数据模态组件传递给父组件

Cha*_*dru 3 ng-bootstrap angular

我尝试下面编码从模态组件到父组件的传递数据.

的package.json

"@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.3"
Run Code Online (Sandbox Code Playgroud)

app.component.html

<button class="btn btn-primary" (click)="openModal()">Open</button>
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

APP-modal.component.html

<h1>{{data}}</h1>
<button class="btn btn-primary" (click)="addMe()"></button>
Run Code Online (Sandbox Code Playgroud)

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

发出后,如何在父组件(app.component)中获取数据?

pko*_*rce 8

你可以这样订阅emitService @Output:

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

虽然上述方法有效,但请注意,通常使用要返回的值关闭模态更容易.这将解决可用的承诺modalRef.有关详细信息,请访问/sf/answers/3053015101/