我正在尝试侦听元素上的指令事件。 Renderer.listen没有接听活动。
HTML代码:
<a click-elsewhere #assignmentOptions>
<pp-click-dropdown [clickElement]="assignmentOptions">
<a>Test Button</a>
</pp-click-dropdown>
</a>
pp-click-dropdown.ts-clickElsewhere()是'click-elsewhere'指令中的指令事件。这是事件正在正确发出。我没有收到任何错误,Renderer.listen只是没有处理指令事件。
import { Component, EventEmitter, Input, Output, Renderer, OnInit } from '@angular/core';
@Component({
selector: 'pp-click-dropdown',
templateUrl: 'panelply-click-dropdown.component.html',
})
export class PanelPlyClickDropdownComponent implements OnInit {
@Input() clickElement: Element;
@Output() onDropdownClick: EventEmitter<any> = new EventEmitter();
private renderer: Renderer;
constructor(_renderer: Renderer) {
this.renderer = _renderer;
}
ngOnInit() {
this.renderer.listen(this.clickElement, 'click', (event) => {
this.toggleDropDown(event);
}); // this line is working properly
this.renderer.listen(this.clickElement, 'clickElsewhere', (event) => {
console.log('clicked oustide')
this.closeDropdown(event);
}); // this line is not working
}
toggleDropDown(e) {
this.isShown = !this.isShown;
this.onDropdownClick.emit(e);
}
closeDropdown(event: Object) {
if (event && event['value'] === true) {
this.isShown = false;
}
}
}
click-elsewhere.ts(伪指令)
import { Directive, ElementRef, EventEmitter, OnDestroy, OnInit, Output, HostListener } from '@angular/core';
import { Subscription } from 'rxjs';
@Directive({
selector: '[click-elsewhere]'
})
export class ClickElsewhereDirective implements OnInit, OnDestroy {
@Output() clickElsewhere: EventEmitter<Object>;
constructor(private _elRef: ElementRef) {
this.clickElsewhere = new EventEmitter();
}
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elRef.nativeElement.contains(targetElement);
if (!clickedInside) {
console.log('clicked outside source')
this.clickElsewhere.emit(null);
}
}
}
我这里缺少什么吗?因为指令事件不是DOM事件,所以侦听不起作用吗?有办法吗?
答案 0 :(得分:0)
这并不是我真正想要的方法,因为我希望将“ click-elsewhere”和“ pp-click-dropdown”模块化,并且我不想以后在不同元素上遇到问题,但是它有效:
<a click-elsewhere (clickElsewhere)="dropdown.isShown = false;" #assignmentOptions>
<pp-click-dropdown #dropdown [clickElement]="assignmentOptions">
<a>Test Button</a>
</pp-click-dropdown>
</a>