我会使用带有选择策略的材料日期选择器
有时候我不应该使用选择策略。
但是就像它是在提供者数组中示例化的一样。我找不到一种方法来有条件地设置它。
import { Component, Injectable, Input } from '@angular/core';
import { DateAdapter } from '@angular/material/core';
import {
MatDateRangeSelectionStrategy,
DateRange,
MAT_DATE_RANGE_SELECTION_STRATEGY,
} from '@angular/material/datepicker';
@Injectable()
export class FiveDayRangeSelectionStrategy<D>
implements MatDateRangeSelectionStrategy<D>
{
constructor(private _dateAdapter: DateAdapter<D>) {}
selectionFinished(date: D | null): DateRange<D> {
return this._createFiveDayRange(date);
}
createPreview(activeDate: D | null): DateRange<D> {
return this._createFiveDayRange(activeDate);
}
private _createFiveDayRange(date: D | null): DateRange<D> {
if (date) {
const start = this._dateAdapter.addCalendarDays(date, -2);
const end = this._dateAdapter.addCalendarDays(date, 2);
return new DateRange<D>(start, end);
}
return new DateRange<D>(null, null);
}
}
/** @title Date range picker with custom a selection strategy */
@Component({
selector: 'app-date-range-picker-selection-strategy',
templateUrl: 'date-range-picker-selection-strategy-example.html',
providers: [
{
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useClass: FiveDayRangeSelectionStrategy,
},
],
})
export class DateRangePickerSelectionStrategyExample {
@Input() set selectionStrategy(value:boolean) {
if(value) {
//// Sould provide selection strategy
}
else {
//// sould not
}
};
}
应用程序.组件.html
<p><b>Sould use selection strategy</b></p>
<app-date-range-picker-selection-strategy [selectionStrategy]="true"></app-date-range-picker-selection-strategy>
<mat-divider></mat-divider>
<p><b>Sould <span [ngStyle]="{'color':'red'}">not</span> use selection strategy</b></p>
<app-date-range-picker-selection-strategy [selectionStrategy]="false"></app-date-range-picker-selection-strategy>
实际上,我创建了两个日期选择器组件:一个有选择策略,一个没有。
我想知道我如何才能在两个用例中只使用一个组件?
我读了很多关于useValue/useFactory/useClass
的书,但我没有找到解决方案。
Stackblitz
1条答案
按热度按时间ogq8wdun1#
您可以尝试使用
useFactory
选项,如下所示: