首页 > 其他 > 详细

[Angular] Angular Global Keyboard Handling With EventManager

时间:2017-07-02 19:38:16      阅读:372      评论:0      收藏:0      [点我收藏+]

If we want to add global event handler, we can use ‘EventManager‘ from ‘@angular/platform-broswer‘.

 

Now we have a modal component, we want to click ‘Esc‘ key to close the modal.

  <au-modal
    class="auth-modal"
    *auModalOpenOnClick="[loginButton, signUpButton]"
    [closeOnClickOutside]="true"
    [closeOnEsc]="true"
    [body]="newModelBody">
    <!-- Modal body -->
  </au-modal>

 

We set two input variables: ‘closeOnEsc‘ for keyboard event. And ‘closeOnClickOutside‘ to click event.

import {Component, Input, OnInit, TemplateRef} from @angular/core;
import {AuModalService} from ./au-modal.service;
import {EventManager} from @angular/platform-browser;

@Component({
  selector: au-modal,
  templateUrl: ./au-modal.component.html,
  styleUrls: [./au-modal.component.scss]
})
export class AuModalComponent implements OnInit {

  @Input() body: TemplateRef<any>;
  @Input() closeOnClickOutside = true;
  @Input() closeOnEsc = true;

  constructor(private auModelService: AuModalService,
              private eventManage: EventManager) {
  }

  ngOnInit() {
    this.eventManage.addGlobalEventListener(window, keyup.esc, () => {
      if (this.closeOnEsc) {
        this.closeModal();
      }
    })
  }

  onClick() {
    if (this.closeOnClickOutside) {
      this.closeModal();
    }
  }

  closeModal() {
    this.auModelService.close();
  }

  cancelCloseModal(evt: KeyboardEvent) {
    evt.preventDefault();
    evt.stopPropagation();
  }

}

 

[Angular] Angular Global Keyboard Handling With EventManager

原文:http://www.cnblogs.com/Answer1215/p/7106848.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!