首页 > 解决方案 > 如何将数据传递给 ng-bootstrap 模态对话框

问题描述

我正在尝试从父组件打开模型。所以,我从父组件打开了一个虚拟对话框,得到了帮助:如何将数据传递给 Angular ng-bootstrap modal 进行绑定。在 Dialog 而不是 dummy text 上,我有输入框来显示来自父组件的信息,同时用户可以编辑此信息并要求将此更改发送回父信息。我尝试使用 tokeninjection 来做 Angular Material MAT_DIALOG 之类的事情,但我并没有完全遵循它。

 import { Component, OnInit, InjectionToken, Injector, OnDestroy, 
  TemplateRef, Inject } from '@angular/core';
  import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';

         export interface CancelDialogData {
            name: string; // this can be any string;
            Comments: string;
         }
        export declare const CUSTOM_DIALOG_DATA: InjectionToken<any>;

          @Component({
           selector: 'app-reject-dialog',
        templateUrl: './reject-dialog.component.html',
           styleUrls: ['./reject-dialog.component.css']
           })
           export class MyDialogComponent implements OnInit {

         constructor(public activeModal: NgbActiveModal,  
       @Inject(CUSTOM_DIALOG_DATA) public data: CancelDialogData) { }

          ngOnInit() {
                 }

              onCancelClick(): void {
                this.activeModal.close();
            }

                }

从父组件:

     const dialogRef = this.modal.open(CancelDialogComponent, data: 
     {name: '', approverComments: ''});

当我尝试传递此数据时,我遇到编译器错误,即数据不是 NgbModalOptions。我真的不明白这里的 InjectionToken,它看起来比@Input/@output 更干净。请协助如何实现它,如 Active material Dialog。

标签: angularmodal-dialogng-bootstrap

解决方案


文档使用:

open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = 'World';
  }

看到如果我们使用按钮“OK”我们在“re”中收到了值,另一种情况(如果“cross”按钮或在模态之外,我们在“dismiss”中收到了“value”

更新了如何收到回复

如果我们想从我们的模态中接收一些值,我们使用 close 函数来发送值。例如,我们的模态 .html 就像

    <div class="modal-header">
      <h4 class="modal-title">Hi there!</h4>
        <!--in function dismiss return a string-->
      <button type="button" class="close" aria-label="Close" 
(click)="activeModal.dismiss('Cross click')">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <p>Hello, <input [(ngModel)]="name">!</p>
    </div>
    <div class="modal-footer">
      <!--but, in function close we return the "name" variable-->
      <button type="button" class="btn btn-outline-dark" (click)="activeModal.close(name)">Aceptar</button>
    </div>

当我们“打开”并收到模态引用时

const modalRef = this.modalService.open(NgbdModalContent)
modalRef.componentInstance.name = 'World';
modalRef.result.then(res=>{
  console.log("CloseButton", res)
},dismiss=>{
  console.log("Cross Button",dismiss)
})

请参阅stackblitz中的示例


推荐阅读