要解决Angular多选下拉框(ng-multiselect-dropdown)在点击外部时不关闭的问题,可以使用以下方法:
import { Component, ElementRef, HostListener } from '@angular/core';
@Component({
selector: 'app-dropdown',
template: `
`,
styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent {
showDropdown: boolean = false;
selectedItems: any[] = [];
constructor(private elementRef: ElementRef) { }
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this.elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.showDropdown = false;
}
}
}
import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
@Component({
selector: 'app-dropdown',
template: `
`,
styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent implements OnInit {
showDropdown: boolean = false;
selectedItems: any[] = [];
@ViewChild('dropdownContent') dropdownContent: ElementRef;
@Output() clickOutside: EventEmitter = new EventEmitter();
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.clickOutside.subscribe(() => {
const clickedInside = this.elementRef.nativeElement.contains(event.target);
if (!clickedInside) {
this.showDropdown = false;
}
});
}
toggleDropdown() {
this.showDropdown = !this.showDropdown;
}
@HostListener('document:click', ['$event'])
public onClick(event) {
this.clickOutside.emit(event);
}
}
通过上述两种方法,你可以在Angular中实现点击外部时下拉框不关闭的功能,无论是使用HostListener还是ViewChild,都可以根据项目需求选择适合的方法。
上一篇:Angular多选下拉菜单