检测角度组件外的点击 [英] Detect click outside Angular component

查看:88
本文介绍了检测角度组件外的点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular中检测点击组件中的点击

code>从'@ angular / core'导入{Component,ElementRef,HostListener,Input};

@Component({
selector:'selector',
template:`
< div>
{{text}}
< / div>
`
})
导出类AnotherComponent {
public text:String;

@HostListener('document:click',['$ event'])
clickout(event){
if(this.eRef.nativeElement.contains(event.target )){
this.text =点击里面;
} else {
this.text =点击外部;



构造函数(private eRef:ElementRef){
this.text ='no clicks yet';
}
}

Plunker工作示例 - 点击这里


How can I detect clicks outside a component in Angular?

解决方案

import { Component, ElementRef, HostListener, Input } from '@angular/core';

@Component({
  selector: 'selector',
  template: `
    <div>
      {{text}}
    </div>
  `
})
export class AnotherComponent {
  public text: String;

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
    } else {
      this.text = "clicked outside";
    }
  }

  constructor(private eRef: ElementRef) {
    this.text = 'no clicks yet';
  }
}

Plunker working example - click here

这篇关于检测角度组件外的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆