Angular2当点击outide div时,它应该是关闭的

时间:2017-05-04 05:06:19

标签: javascript jquery angular

这里的代码,当我cliktoshow方法然后它显示div。当我点击该div的outide时,它必须隐藏自己。

      public hideElement: boolean = false;   

       clicktoshow()
       {
           this.organizedetailsshow = false;
           if (this.hideElement) {
           this.hideElement = false;
      }
     else {
         this.hideElement = true;
    }
    } 
    
    outsidehide(e)
         {
           console.log("event",e)
           if(this != $("#myDiv")[0]) {
             this.hideElement = false;
           }
         }(e)
         {
           console.log("event",e)
           if(this != $("#myDiv")[0]) {
             this.hideElement = false;
           }
         }
  <div>
    <div>
    <button (click)= "clicktoshow()">  Click to show  button </button>
    <div !hideElement (click)=outsidehide($event)> 
         hi 
      </div>
                 <p> Hi hello </p>
  </div>

这里的代码,当我cliktoshow方法然后它显示div。当我点击outide那个div时,它必须隐藏自己。

2 个答案:

答案 0 :(得分:0)

<span style="background-color:red;width:50px;height:50px" *ngIf="isDivHide" id="testBox"> Testing </span>

<button (click)="bounce()" id="btn"> Bounce me </button>

如果以上是你的html而且MyAnimation是你对应的组件,那么你可以像这样配置你的组件,

@Component({
    selector: 'my-anim',
    templateUrl: 'App/Animation/animation.html',
    host: {
        '(document:click)': 'onClick($event)',
    }
})

export class MyAnimation {
    animationService = null;

    isDivHide = false;

    onClick = function (event) {
        if (!$(event.target).is($('#testBox') ) && !$(event.target).is($('#btn')) ){ 
            // Hide the test box
            this.isDivHide = false;
        }
    }

    bounce = function () {
        this.isDivHide = true;
        }

    constructor() {
        this.isDivHide = false;
    }
}

解释

host: {
    '(document:click)': 'onClick($event)',
}

这会将document的点击事件绑定到onClick()功能。

因此,每次单击文档时,此功能都会触发。所以要小心使用这个功能。

onClick = function (event) {
    if (!$(event.target).is($('#testBox') ) && !$(event.target).is($('#btn')) ){ 
        // Hide the test box
        this.isDivHide = false;
    }
}

在这里,您要检查被点击的元素是您的testBox还是按钮。如果否,则隐藏您的测试框。

这就是全部!!!

希望这会对你有所帮助。

答案 1 :(得分:0)

因为您的方案是隐藏元素而不是操纵DOM结构,所以您可以创建一个属性指令以应用于<div>

找到一个解决方案:

<强>指令

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

@Directive({
  selector: '[showMe]'
})
export class ShowMeDirective {

  private _show: boolean;

  /**
   * Emmit changes in 'showMe'.
   * @type {EventEmitter}
   */
  @Output('showMeChange')
  public showChange = new EventEmitter();

  /**
   * Called when the 'showMe' expression changes.
   * @param show Whether to show or hide the element.
   */
  @Input('showMe')
  public set show(show: boolean) {
    this.elRef.nativeElement.style.display = show ? null : 'none';
    this._show = show;
  }

  /**
   * Get whether the element is visible.
   * @returns {boolean}
   */
  public get show() {
    return this._show;
  }

  /**
   * Ctor.
   * @param elRef References the element
   */
  constructor(private elRef: ElementRef) {
  }

  /**
   * Stop propagating click event for current element.
   * @param $event Event arguments
   */
  @HostListener('click', ['$event'])
  public onElementClick($event) {
    $event.stopPropagation();
  }

  /**
   * When the document is clicked then the element is hidden.
   */
  @HostListener('document:click')
  public onDocumentClick() {
    if (this.show !== false) {
      this.show = false;
      this.showChange.emit(false);
    }
  }
}

<强>用法

<div [(showMe)]="show" style="line-height: 50px; font-weight: bold;">
  Contents of DIV
</div>

<p>DIV is visible: {{ show }}</p>
<br/>

<button (click)="show = true; $event.stopPropagation();" type="button">Show DIV</button>

show最初设置为一个值(例如:show = false)。

<强>解释

showMe指令定义了一个输入(用@Input注释),它是指令属性本身showMe。这允许从外部传递该值并相应地做出反应。因此,这是一个设置style.display值并触发更改事件的setter。

showMe指令还定义了一个输出(用@Output注释),称为showMeChange。这是为了反映模型中的更改,以便使用该指令的组件将相应地更改其属性。

showMe指令使用click订阅应用它的元素的@HostListener('click', ['$event'])事件。因此,单击时,事件不会传播,因此document.click处理程序不会截获该事件。

showMe指令订阅document.click事件,以使元素不可见。

<button>处理click事件,但他也通过执行click阻止$event.stopPropagation();冒泡到其他元素。

由于showMe指令定义了showMe输入和showMeChange输出,因此可以将其写为<div [showMe]="show" (showMeChange)="show = $event;">。但它也可以写成<div [(showMe)]="show">(香蕉盒式)。

因此,您可以从指令中操纵可见性,也可以从指令外部操纵可见性,从而来回传递数据。

注意:以下if代码可防止在指令中未更改值时触发事件:

  public onDocumentClick() {
    if (this.show !== false) {
      this.show = false;
      this.showChange.emit(false);
    }
  }