【问题标题】:EventEmitter from bootstrap modal component to parent从引导模式组件到父级的 EventEmitter
【发布时间】:2017-12-30 15:15:47
【问题描述】:

我在 Angular 4 中使用 ng-bootstrap,具体用例是“组件作为内容”的模式(来自https://ng-bootstrap.github.io/#/components/modal/examples 的第二个场景)。

我想从子级向父级发送一些数据。为此,我从示例中创建了一个无效的 plunk:

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

【问题讨论】:

    标签: angular ng-bootstrap


    【解决方案1】:

    其实非常很简单,你可以直接订阅作为模态内容打开的组件的@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);
        })
      }
    }
    

    这是一个正常工作的插件:http://plnkr.co/edit/rMJ7qfSSLK0oHspIJbDB?p=preview

    旁注:我不确定您的确切用例是什么,但Event emitter from bootstrap modal to parent 的答案显示了模态打开器和用作模态内容的组件之间的首选通信方法。 p>

    【讨论】:

    • 效果很好!作为 ng2 学习者,我不知道您可以简单地订阅 componentInstance。文档和教程通常会教您在模板中添加事件绑定(例如,html 标记中的 (clickevent)="function")。由于模板中没有添加事件绑定的标签(只有 open() 函数),我不确定在哪里添加它。这帮助很大。
    • 谢谢。对于带有 ngx-bootstrap 的 angular2,我只需要使用“content”代替“componentInstance”。
    • modalRef.componentInstance 在 Angular 7 中不可用,它给我带来了错误
    • @Veshraj Joshi 你可以使用modelRef.content 而不是@Ali Faizan 所说的modalRef.componentInstance
    • @AsadShakeel 我在stackoverflow.com/questions/42681556/… 写了答案,感谢您的评论。请检查是否正确。
    猜你喜欢
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2021-05-06
    • 2021-07-30
    • 2018-03-11
    相关资源
    最近更新 更多