问题
I upgraded my Angular from 4 to 6, and consequently had a problem with my click-off policy, it stopped working on all components.
my directive:
import { Directive, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
constructor(private _elementRef : ElementRef) { }
@Output()
public clickOutside = new EventEmitter();
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}
My component.html that makes use of this directive:
<div id="sidenav" *ngIf="this.opened" class="sidenav" [ngClass]="getClasses()" [ngStyle]="getStyles()" clickOutside (clickOutside)="closeOutsideSidenav()">
<header> {{ navTitle }} </header>
<i *ngIf="this.showCloseButton" class="iconic iconic-x-thin close-icon" (click)="closeSidenav()"></i>
<ng-content></ng-content>
</div>
<div *ngIf="this.backdrop && this.opened" class="sidenav-backdrop"></div>
回答1:
You're referencing "this" in your template, which is not necessary. I made a working example of that directive:
https://stackblitz.com/edit/angular-piqewb
And theres no reason to have the directive on the div twice.
<div id="sidenav" *ngIf="opened" class="sidenav" [ngClass]="getClasses()" [ngStyle]="getStyles()" (clickOutside)="closeOutsideSidenav()">
<header> {{ navTitle }} </header>
<i *ngIf="showCloseButton" class="iconic iconic-x-thin close-icon" (click)="closeSidenav()"></i>
<ng-content></ng-content>
</div>
<div *ngIf="backdrop && opened" class="sidenav-backdrop"></div>
回答2:
view:
<div #insideElement></div>
component:
export class SomeClass {
@ViewChild("insideElement") insideElement;
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this.insideElement.nativeElement.contains(targetElement);
if (!clickedInside) {
console.log('outside clicked');
}
}
}
回答3:
Run the inside NgZone
.
Example:
export class AppComponent {
opened: boolean = false;
constructor(private ngZone: NgZone) {
}
closeOutsideSidenav(e) {
this.ngZone.run(() => {
this.opened = !this.opened;
})
}
}
I added my code to stackblitz. https://stackblitz.com/edit/angular-gyhtym (click outside of the "Highlight Me!")
来源:https://stackoverflow.com/questions/50531212/directive-click-outside-angular-6