我正在嘗試使用自定義 MAT_DATE_RANGE_SELECTION_STRATEGY 以角度方式實作日期選擇器。這允許用戶選擇 14 天的范圍。

使用以下代碼(取自 angular 檔案)來實作自定義策略
@Injectable()
export class FourteenDayRangeSelectionStrategy<D> implements MatDateRangeSelectionStrategy<D> {
constructor(private _dateAdapter: DateAdapter<D>) {}
selectionFinished(date: D | null): DateRange<D> {
return this._createFourteeDayRange(date);
}
createPreview(activeDate: D | null): DateRange<D> {
return this._createFourteeDayRange(activeDate);
}
private _createFourteeDayRange(date: D | null): DateRange<D> {
if (date) {
const start = this._dateAdapter.addCalendarDays(date, 0);
const end = this._dateAdapter.addCalendarDays(date, 13);
return new DateRange<D>(start, end);
}
return new DateRange<D>(null, null);
}
}
并將其注入組件中,如下所示。
@Component({
selector: 'app-awesomecomponent',
templateUrl: './awesomecomponent.component.html',
styleUrls: ['./awesomecomponent.component.css'],
providers: [{
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useClass: FourteenDayRangeSelectionStrategy
}]
})
但是,當用戶選擇允許自定義日期范圍復選框(如上圖所示)時,我希望禁用自定義策略并允許用戶選擇任何日期范圍。
我怎樣才能實作這個功能?我假設,我們需要從組件中動態洗掉下面以允許任何日期選擇。但是我不知道該怎么做。
providers: [{
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useClass: FourteenDayRangeSelectionStrategy
}]
請幫忙。
uj5u.com熱心網友回復:
您在github 中有 MatDateRangeSelectionStrategy 的來源,因此您可以使用變數來激活或關閉策略。
export class FourteenDaySelectionStrategy<D>
implements MatDateRangeSelectionStrategy<D>
{
constructor(private _dateAdapter: DateAdapter<D>) {}
off: boolean = false; //--use a variable "off"
selectionFinished(date: D | null, currentRange: DateRange<D>): DateRange<D> {
if (!this.off) return this._createFourteenDayRange(date);
//see that al the code below is the code of the github
let { start, end } = currentRange;
if (start == null) {
start = date;
} else if (
end == null &&
date &&
this._dateAdapter.compareDate(date, start) >= 0
) {
end = date;
} else {
start = date;
end = null;
}
return new DateRange<D>(start, end);
}
createPreview(
activeDate: D | null,
currentRange: DateRange<D>
): DateRange<D> {
if (!this.off) return this._createFourteenDayRange(activeDate);
//see that al the code below is the code of the github
let start: D | null = null;
let end: D | null = null;
if (currentRange.start && !currentRange.end && activeDate) {
start = currentRange.start;
end = activeDate;
}
return new DateRange<D>(start, end);
}
private _createFourteenDayRange(date: D | null): DateRange<D> {
if (date) {
const start = date;
const end = this._dateAdapter.addCalendarDays(date, 14);
return new DateRange<D>(start, end);
}
return new DateRange<D>(null, null);
}
現在,您需要注入 MatDateRangeSelection 并使用 getter 來更改變數的值 off
constructor(
@Inject(MAT_DATE_RANGE_SELECTION_STRATEGY)
private rg: FourteenDaySelectionStrategy<any>
) {}
get customRange() {
return this.rg.off;
}
set customRange(value) {
this.rg.off = value;
}
帶有[(ngModel)]完整代碼的復選框
查看堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342730.html
下一篇:如何在自定義指令中使用屬性系結?
