【问题标题】:Modal closing when clicking outside it - needs to call same function as when clicked on close modal button in Angular 2单击外部时模态关闭 - 需要调用与单击 Angular 2 中的关闭模态按钮时相同的函数
【发布时间】:2018-08-23 10:57:45
【问题描述】:

当单击关闭模式按钮以及在模式外单击鼠标时,模式会关闭 我想调用与单击关闭模态按钮时调用的相同函数,以及单击模态外部时调用的函数。我不确定如何在 Angular 2 中执行此操作。请您分享您的想法。 此外,我的 Modal 是我的主要 html 的一部分,它没有单独的组件或 html ...... 谢谢

import { Component, OnInit, NgModule, Input, Output, EventEmitter, ViewChild, ElementRef } from '@angular/core';
import * as jQuery from 'jquery';

export class Component implements OnInit {

  @ViewChild('newModal') newModal: ElementRef; 

public OpenModal(){
jQuery(this.newModal.nativeElement).modal('show');
}
public CloseModal(){
Includes actions taken when close modal button is clicked - I want the same function to be called with I click outside the model
}        
}

我在 html 中尝试了以下内容,但每当我单击组件上的任何位置而不是模式区域时,它就会运行。

(clickOutside)="CloseModal()"; 

【问题讨论】:

  • 你用什么来创建模态,引导程序?一些角度库?您需要挂钩任何发生的事件并调用相同的代码。
  • 嗨,Jason,我已经更新了我的问题并提供了更多详细信息,请查看并分享您的意见

标签: angular angular2-template angular2-forms angular2-directives


【解决方案1】:

如果你使用的是 NgbModel

import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';

然后像这样调用它的内部构造函数:

constructor(private modalService: NgbModal)

并调用它自己的方法:

this.modalService.dismissAll();

无需传递任何参数

【讨论】:

    【解决方案2】:

    我通过添加一个用于在本机元素外部单击并更改某些条件的功能来解决它​​,它对我有用....

    【讨论】:

      【解决方案3】:

      是的,根据您使用的模态,这很容易。通常每个模态对话都有一个 onDismiss()-Observable,你可以订阅它。为了确保它已经被实例化,已经在 AfterViewInit 中执行您的订阅。

      ngAfterViewInit() {
      
        // react on modal closed by clicking beside it
        this.newModal.onDismiss.subscribe(() => {
          // here goes your code then
        });
      
      }
      

      这对我来说一直都很完美。

      【讨论】:

      • 嗨 DiabolicWords 我是 Angular 新手 我尝试按照您提到的方式使用 ngAfterViewInit 但我收到错误消息“无法读取未定义的属性'订阅'”我不确定我应该订阅什么. ngAfterViewInit() { this.newModal.onDismiss.subscribe(() => { this.CloseModal(); }); console.log("ngAfterViewInit"); }
      • 哦,我明白了。好吧,我实际上正在使用 ModalComponent 并且在通过 jQuery 处理模态时没有经验。对不起!也许这行得通,但只是嬉皮笑脸: ngAfterViewInit() { jQuery(this.newModal.nativeElement).modal('onDismiss').subscribe(() => { // 这是你的代码然后 }); }
      • 这对我不起作用,因为我的 Modal 是我的 html 的一部分并且它没有单独的组件你知道任何其他的生命周期钩子可以与内部子模态以相同的方式工作吗?
      • 我在 ngAfterViewInit 中订阅了onDismiss 事件,它就像一个魅力!谢谢。
      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 2014-09-16
      • 1970-01-01
      • 2019-04-26
      • 2020-07-30
      • 2020-03-11
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多