如何在angular 4中使用ng-bootstrap将数据模式组件传递给父组件 [英] How to pass data modal Component to parent Component using ng-bootstrap in angular 4

查看:64
本文介绍了如何在angular 4中使用ng-bootstrap将数据模式组件传递给父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
    }
}

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

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

推荐答案

您可以像这样订阅emitService @Output:

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

虽然上述方法可行,但请注意,通常只用要返回的值关闭模式,这会更容易.这将解决modalRef上可用的承诺.有关更多详细信息,请参见 https://stackoverflow.com/a/43614501/1418796

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

这篇关于如何在angular 4中使用ng-bootstrap将数据模式组件传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆