Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clickoutside指令 #50

Open
alanhe421 opened this issue May 31, 2018 · 0 comments
Open

Clickoutside指令 #50

alanhe421 opened this issue May 31, 2018 · 0 comments

Comments

@alanhe421
Copy link
Owner

alanhe421 commented May 31, 2018

场景

当我们展开某个弹出层,我们点击弹出层外部任意位置,实现弹出层关闭,如何实现呢,一个指令即可搞定。

click-outside.directive.ts

import {Directive, ElementRef, EventEmitter, HostListener, Output} from '@angular/core';

/**
 * Created by He on 25/12/17.
 * 点击挂载对象的外部节点,触发事件
 */
@Directive({
  selector: '[appClickOutside]'
})
export class ClickOutsideDirective {
  @Output() clickOutside = new EventEmitter();

  constructor(private elementRef: ElementRef) {
  }

  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
    const clickedInside = this.elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.clickOutside.emit(null);
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant