【问题标题】:Is it possible to send data without selector in Angular?是否可以在没有选择器的情况下在 Angular 中发送数据?
【发布时间】:2019-07-05 11:14:26
【问题描述】:

我想将数据从孩子发送给父母。 但是我没有在父 html 代码中使用子选择器,因为它是 Angular Material 的对话框,只使用“MatDialogRef”和“dialog.open()” 在这种情况下,我不能使用“EventEmiter”。单击对话框面板时如何发送数据?

【问题讨论】:

  • 如果您没有使用选择器,那么它就不是真正的孩子,是吗?如果是孩子,您可以使用@ViewChild,但我不确定在这种情况下是否可行。您也许可以订阅对话框关闭事件并从中获得所需的信息,但没有代码就很难提供帮助。

标签: angular data-binding


【解决方案1】:

首先,您的问题非常模糊,我认为很多人(包括我自己)都无法理解您的问题。但是,我将成为先知,并猜测您正在使用MatDialogue 并希望从中获取一些数据。 您可以通过两种方式实现这一点,具体取决于您的架构以及您如何启动对话。

  1. 将父对象作为输入传递给要操作的对话,因此您可以自动在父级别上进行更改,就像您可以在此链接中找到的示例一样 https://stackblitz.com/angular/njdkroaomnb?file=app%2Fdialog-overview-example-dialog.html
  2. 使用@Output() 发出对象并在实现此对话视图的父级上收听它。在这种情况下,您可以按照以下步骤操作:

    • 制作你的模态对话组件myModal.component.html并实现show函数如下:

<button (click)="onOpenClicked(content)" class="btn btn-primary" style="width:100%">
Open Modal</button>
<!-- Modal -->
<ng-template #content let-modalCon let-c="close" let-d="dismiss">
  <div class="modal-header">
    <h5 class="modal-title" id="modal-basic-title">Create User</h5>
  </div>
  <div class="modal-body">
  PPut the body of the modal here
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" (click)="closeContent()">
      Cancel</button>
    <button type="button" class="btn btn-success" (click)="confirm()">Confirm</button>
  </div>
</ng-template>
  • 在底层控制器上myModal.component.ts实现以下必要功能

constructor(
    config: NgbModalConfig,
    private modalService: NgbModal) {
    // Customize default values of modals used by this component tree
    config.backdrop = 'static';
    config.keyboard = false;
  }
  
  @Output() public confirmEventEmitter = new EventEmitter();

  modalReference: any;
  onOpenClicked(content) {
      this.modalReference = this.modalService.open(content, { centered: false });
    }
  confirm() {
  this.confirmEventEmitter.emit('WhateverObjectYouHave');
  this.modalReference.close();
  }
  closeContent() {
  this.modalReference.close();
  }
  • 然后,您可以在另一个组件中使用此模态组件,方法是将相应的标签导入目标组件的 DOM,并在模态组件发出如下值时调用函数: &lt;app-myModal (confirmEventEmitter)="onConfirmEventEmmited($event)"&gt;&lt;/app-myModal&gt; 其中onConfirmEventEmmited(event:any) 是您主机的component.ts 文件中的一个函数。 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2013-11-07
    • 1970-01-01
    • 2018-08-01
    • 2021-03-24
    相关资源
    最近更新 更多