2017-07-24 48 views
3

我对Angular 4使用ng-bootstrap,具体使用案例是以“组件作为内容”(第二种方案,从https://ng-bootstrap.github.io/#/components/modal/examples)开始的模式。EventEmitter从引导模式组件到父

我想从孩子向父母发出一些数据。为此,我创建了从例如非工作普拉克:

modal.component.ts

import {Component, Input, Output, EventEmitter} from '@angular/core';  
import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap'; 

@Component({ 
    selector: 'ngbd-modal-content', 
    template: ` 
    <div class="modal-header"> 
     <h4 class="modal-title">Hi there!</h4> 
    </div> 
    <div class="modal-body"> 
     <p>Hello!</p> 
    </div> 
    <div class="modal-footer"> 
     <button type="button" class="btn btn-secondary" (click)="testclick('teststring')">Testclick</button> 
    </div> 
    ` 
}) 
export class NgbdModalContent { 
    @Output() clickevent = new EventEmitter<string>(); 

    constructor(public activeModal: NgbActiveModal) {} 

    testclick(teststring: string) { 
    this.clickevent.emit(teststring); 
    } 
} 

@Component({ 
    selector: 'ngbd-modal-component', 
    templateUrl: 'src/modal-component.html' 
}) 
export class NgbdModalComponent { 
    constructor(private modalService: NgbModal) {} 

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

modal.component.html

<button class="btn btn-lg btn-outline-primary" (click)="open()">Launch demo modal</button> 

正如你所看到的,我只有将EventEmitter添加到NgbdModalContent组件中。我想要的是NgbdModalComponent接收testclick事件并将其记录到控制台。我在哪里可以把它放在上面的代码中?

我知道这里有一个非常类似的问题Event emitter from bootstrap modal to parent但我认为它仍然是一个非常不同的实现方案,因为我直接打开模块作为组件在这里。

很显然,我宁愿一些简单的解决方案,我没有去成modalService本身的代码...

回答

11

它实际上是非常简单的,你可以直接订阅组件的@Output事件打开,模式的内容:

export class NgbdModalComponent { 
    constructor(private modalService: NgbModal) {} 

    open() { 
    const modalRef = this.modalService.open(NgbdModalContent); 
    modalRef.componentInstance.name = 'World'; 
    modalRef.componentInstance.clickevent.subscribe(($e) => { 
     console.log($e); 
    }) 
    } 
} 

这里是一个工作plunker:http://plnkr.co/edit/rMJ7qfSSLK0oHspIJbDB?p=preview

附注:我不知道你是什么精确使用案例,但回答Event emitter from bootstrap modal to parent显示模式开启器和用作模式内容的组件之间的首选通信方法。

+0

这很好用!作为一名ng2学习者,我不知道你可以简单地订阅componentInstance。文档和教程通常会教你在模板中添加事件绑定(例如,(clickevent)=“function”)。由于模板中没有标签来添加事件绑定(只有open()函数),所以我不确定在哪里添加它。这帮了很多。 – Ruehri

+0

谢谢。对于使用ngx-bootstrap的angular2,我只需使用“content”来代替“componentInstance”。 – ali