我有一个组件,在该组件中我切换一个布尔变量,以便在单击图像时显示和隐藏菜单。
html看起来像这样:
<img src="../../assets/image/dropdown.png" class="dropdown-image" (click)="toggleDropDownMenu()">
<div class="dropdown-content" [hidden]="dropDownMenu">
<a class="menu-item" (click)="showTerms()">Policy</a>
<a class="menu-item" (click)="showProfile()">Profile</a>
<a class="menu-item" (click)="logOut()">Log Out</a>
</div>
toggleDropdownMenu()如下:
public toggleDropDownMenu(): void {
this.dropDownMenu = !this.dropDownMenu;
}
因此,当我点击按钮时,我可以显示并隐藏菜单选项。
我想要进一步实现的目的是隐藏菜单,当用户点击菜单元素外部时也是如此。经过一番搜索,我发现了一个指令的概念。我用以下方式实现了这个想法:
import { Directive, ElementRef, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
console.log("clicked inside");
} else {
console.log("clicked outside");
}
}
constructor(private eRef: ElementRef) {
console.log(" not clicked");
}
}
当我在元素内部或外部单击时,我在控制台中获得正确的消息,这是有效的。我想做的是能够在我的html上写这样的东西:
<img src="../../assets/image/dropdown.png" class="dropdown-image" (click)="toggleDropDownMenu()"
(clickOutside)="closeMenu()">
<div class="dropdown-content" [hidden]="dropDownMenu">
<a class="menu-item" (click)="showTerms()">Policy</a>
<a class="menu-item" (click)="showProfile()">Profile</a>
<a class="menu-item" (click)="logOut()">Log Out</a>
</div>
有办法吗?
有例子吗?
答案 0 :(得分:0)
我不确定你是什么意思'知道constructo的参数是什么“,但是为了捕获点击事件并检查事件是否在你的组件中,你可以做以下事情:
@Component({
selector: 'ab-some-component',
templateUrl: './some-component.html',
styleUrls: ['./some-component.scss'],
host: {
'(document:click)': 'documentClickListener($event)',
},
})
export class SomeComponent{
constructor(private elementRef: ElementRef) {
}
/**
* Listen for document click event.
* Check's if a click outside of this element
*/
documentClickListener(event): void {
if (!this.elementRef.nativeElement.contains(event.target))
//Click event occur outside of this component bounds.
}
}
基本上我们在这里做的是在主机级别声明文档点击事件监听器并分配到本地组件功能。 然后检查包含click事件目标的元素ref(在构造函数中注入)。 希望它有所帮助。
答案 1 :(得分:0)
尝试使用@Output EventEmitters
//directive.ts
import { Directive, ElementRef, EventEmitter, Output, HostListener } from '@angular/core';
@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {
@Output() clickInside:EventEmitter<any> = new EventEmitter();
@Output() clickOutside:EventEmitter<any> = new EventEmitter();
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
console.log("clicked inside");
this.clickInside.emit(null);
} else {
console.log("clicked outside");
this.clickOutside.emit(null);
}
}
constructor(private eRef: ElementRef) {
console.log(" not clicked");
}
}
然后在你的组件中
<img src="../../assets/image/dropdown.png" class="dropdown-image"
(clickInside)="toggleDropDownMenu()" (clickOutside)="closeMenu()">