我正在使用 Angular 技术开发应用程序,我遇到了这个问题,并到处寻找如何使用 Angular Material 提供解决方案,但没有,我设法用以下方法解决了它(代码可以改进):
在文件 html 中:
<mat-form-field appearance="fill">
<mat-label>date</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate placeholder="Start date" formControlName="mesIni">
<input matEndDate placeholder="End date" formControlName="mesFin">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker id="picker" #picker disabled="false" startView="multi-year"
(monthSelected)="chosenMonthHandler($event, picker)" (click)="true">
</mat-date-range-picker>
</mat-form-field>
在文件 ts 中:
formBusqueda: FormGroup;
//flag to identify if the start date or end date is entered
mclick = 0;
ngOnInit() {}
get controls() {
return this.formBusqueda.controls;
}
public chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>):void {
this.mclick++;
if (this.mclick == 1) {
const ctrlValue = this.controls.mesIni.value;
ctrlValue.month(normalizedMonth.month());
this.controls.mesIni.setValue(ctrlValue);
datepicker.close();
//It can improve
var inter = setInterval(() => {
let htmlElem: HTMLCollectionOf<HTMLElement> = document.getElementsByClassName('mat-focus-indicator mat-icon-button mat-button-base') as HTMLCollectionOf<HTMLElement>;
//Here it is important to put the id of the element that is clicked to open the calendar
htmlElem[1].click();
clearInterval(inter);
}, 50);
} else if (this.mclick == 2) {
const ctrlValue = this.controls.mesFin.value;
ctrlValue.month(normalizedMonth.month());
this.controls.mesFin.setValue(ctrlValue);
datepicker.close();
this.mclick = 0;
}
}
诀窍是延迟关闭并重新打开日历,这并不理想,但它是一种解决方法。