我创建了一个有角度的日期范围选择器。但是我面临一个问题。我无法关闭下拉菜单。我在下面共享我的代码。
daterangepicker.html
<form formGroup="dateForm">
<div class="d-flex">
<mat-form-field>
<input matInput placeholder="Start Date" formControlName="start" [value]="startDate? startDate: ''">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Choose a date" formControlName="end" [value]="endDate? endDate: ''"
(click)="toggleDropDown()" (blur)="closeDropDown()">
</mat-form-field>
</div>
</form>
<div class="d-flex" *ngIf="showDropdown">
<mat-card>
<p>Start Date</p>
<mat-calendar (selectedChange)="updateStart($event)"></mat-calendar>
</mat-card>
<mat-card>
<p>End Date</p>
<mat-calendar (selectedChange)="updateEnd($event)"></mat-calendar>
</mat-card>
</div>
daterangepicker.ts
import { Component, OnInit, ChangeDetectorRef } from "@angular/core";
import { FormControl, FormGroup, FormBuilder } from "@angular/forms";
import { MatDatepickerInputEvent } from "@angular/material/datepicker";
@Component({
selector: "date-range-picker",
templateUrl: "./date-range-picker.component.html",
styleUrls: ["./date-range-picker.component.scss"],
})
export class DateRangePickerComponent implements OnInit {
events: string[] = [];
showDropdown: boolean;
dateForm: FormGroup;
startDate: any;
endDate: any;
constructor(private fb: FormBuilder, private changeDetectorRef: ChangeDetectorRef) {}
ngOnInit(): void {
this.dateForm = this.fb.group({
start: new FormControl(),
end: new FormControl(),
});
}
toggleDropDown(): void {
this.showDropdown = !this.showDropdown;
console.log("clicked");
}
closeDropDown(): void {
this.showDropdown = false;
console.log("clicked outside");
}
updateStart(event: any): void {
this.startDate = event;
}
updateEnd(event: any): void {
this.endDate = event;
}
}
有人可以帮助我解决此问题。下拉菜单正在打开。但是,每次我尝试选择一个日期时,下拉列表都会关闭。
答案 0 :(得分:0)
constructor(private fb: FormBuilder, private changeDetectorRef: ChangeDetectorRef) {
if (document.getElementById('showDropDown')) {
if (document.getElementById('showDropDown').contains(e.target)) {
this.showDropdown = true;
} else {
this.showDropdown = false;
}
}
}
在HTML
<div class="d-flex" id="showDropDown">
<mat-form-field>
<input matInput placeholder="Start Date" formControlName="start" [value]="startDate? startDate: ''">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Choose a date" formControlName="end" [value]="endDate? endDate: ''"
(click)="toggleDropDown()" (blur)="closeDropDown()">
</mat-form-field>
</div>
我只是放置演示ID。放置在您需要的任何地方。