要关闭所有下拉菜单,需要使用ViewChildren,而不是ViewChild。这将返回与选择器匹配的所有元素或指令的查询。
我的Angular应用程序中有两个下拉菜单:
<div class="input-group">
<input
id="startDate"
type="text"
class="form-control"
aria-label="Start date"
dlDateTimeInput
[ngModel]="startDate"
/>
<div ngbDropdown class="d-inline-block">
<div class="input-group-append">
<button
class="btn btn-outline-primary"
id="startDateDropdown"
ngbDropdownToggle
>
<i class="oi oi-calendar"></i>
</button>
<div ngbDropdownMenu aria-labelledby="startDateDropdown">
<div style="width: 360px">
<dl-date-time-picker
[(ngModel)]="startDate"
(change)="startDateSelected($event)"
minuteStep="15"
>
</dl-date-time-picker>
</div>
</div>
</div>
</div>
</div>
<div class="input-group">
<input
id="endDate"
type="text"
class="form-control"
aria-label="End date"
dlDateTimeInput
[ngModel]="endDate"
/>
<div ngbDropdown class="d-inline-block">
<div class="input-group-append">
<button
class="btn btn-outline-primary"
id="endDateDropdown"
ngbDropdownToggle
>
<i class="oi oi-calendar"></i>
</button>
<div ngbDropdownMenu aria-labelledby="endDateDropdown">
<div style="width: 360px">
<dl-date-time-picker
[(ngModel)]="endDate"
(change)="endDateSelected($event)"
minuteStep="15"
>
</dl-date-time-picker>
</div>
</div>
</div>
</div>
</div>
我正试图用以下内容关闭下拉菜单:
import { ViewChild } from "@angular/core";
import { NgbDropdown } from "@ng-bootstrap/ng-bootstrap";
[...]
export class ParentComponent {
@ViewChild(NgbDropdown)
private dropdown: NgbDropdown;
public startDateSelected(event: DlDateTimePickerChange<Date>): void {
this.startDatePicked.emit(event.value);
this.dropdown.close();
}
public endDateSelected(event: DlDateTimePickerChange<Date>): void {
this.endDatePicked.emit(event.value);
this.dropdown.close();
}
}
问题
问题是只有第一个下拉列表被关闭,但第二个没有。
如何同时关闭开始下拉列表和结束下拉列表?
@ViewChildren(NgbDropdown)
dropdowns: QueryList<NgbDropdown>;
startDateSelected(event: DlDateTimePickerChange<Date>): void {
this.startDatePicked.emit(event.value);
this.closeDrownDowns();
}
endDateSelected(event: DlDateTimePickerChange<Date>): void {
this.startDatePicked.emit(event.value);
this.closeDrownDowns();
}
private closeDropDowns() {
this.dropdowns?.forEach(x => x.close());
}