在使用Angular Material Datepicker时,您可以使用mat-date-range-input指令将开始和结束日期选择器组合起来,以便选择日期范围。但是,如果您想获取这个选择器所选日期范围的值,您需要使用Angular Material Datepicker的选择策略API。
以下示例显示如何使用选择策略来获取所选日期范围的值。 要获取所选日期范围,请使用selectionChanged事件,并将当前日期范围作为参数传递。 请注意,这将返回一个MatDateSelectionModel对象,该对象包含开始和结束日期。
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDateSelectionModel, MatDateRangeSelectionStrategy } from '@angular/material/datepicker';
@Component({
selector: 'app-datepicker-range-example',
templateUrl: 'datepicker-range-example.html',
styleUrls: ['datepicker-range-example.css'],
})
export class DatepickerRangeExample {
startDate = new FormControl();
endDate = new FormControl();
constructor(private selectionStrategy: MatDateRangeSelectionStrategy) {}
onSelect(selection: MatDateSelectionModel): void {
const range = this.selectionStrategy.selectionFinished(
selection.selection, selection.source === 'start' ? 'end' : 'start'
);
if (range.start && range.end) {
console.log('Range:', range);
}
}
}