我會使用帶有選擇策略的材料日期選擇器
有時我不應該使用選擇策略。
但就像它在 providers array 中實體化一樣。我找不到有條件地設定它或不設定它的方法。
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但我沒有找到解決方案。
堆疊閃電戰
uj5u.com熱心網友回復:
您可以嘗試使用useFactory如下選項:
@Component({
selector: 'app-date-range-picker-selection-strategy',
templateUrl: 'date-range-picker-selection-strategy-example.html',
providers: [
{
provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
useFactory: (
comp: DateRangePickerSelectionStrategyExample,
adapter: DateAdapter<unknown>
) => {
return comp.selectionStrategy
? new FiveDayRangeSelectionStrategy(adapter)
: null;
},
deps: [DateRangePickerSelectionStrategyExample, DateAdapter],
},
],
})
export class DateRangePickerSelectionStrategyExample {
@Input() selectionStrategy!: boolean;
}
分叉的 Stackblitz
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537505.html
下一篇:在C#中使用多執行緒時的性能問題
