首页 文章

EventSmitter从bootstrap模态组件到parent

提问于
浏览
16

我在Angular 4中使用ng-bootstrap,具体用例是"Component as content"的模态(来自https://ng-bootstrap.github.io/#/components/modal/examples的第二个场景) .

我想从孩子那里向父母发出一些数据 . 为此,我从示例中创建了一个非工作插件:

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 本身的代码......

1 回答

  • 37

    它实际上非常简单,因为您可以直接订阅作为模态内容打开的组件的 @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的答案显示了模态开启器和用作模态内容的组件之间的首选通信方法 .

相关问题