1

I would like to inject conditionally a service depending on @Input value

service.ts

import { Injectable } from '@angular/core';
import { DateAdapter } from '@angular/material/core';
import {
  MatDateRangeSelectionStrategy,
  DateRange,
} 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);
  }
}

component.ts

import { Component } from '@angular/core';
import { MAT_DATE_RANGE_SELECTION_STRATEGY } from '@angular/material/datepicker';
import { SelectionStrategy } from './selectionStrategy.service';

/** @title Date range picker with custom a selection strategy */
@Component({
 selector: 'date-range-picker-selection-strategy-example',
 templateUrl: 'date-range-picker-selection-strategy-example.html',
 providers: [
   {
     provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
     useClass: SelectionStrategy,
   },
 ],
})
export class DateRangePickerSelectionStrategyExample {}
@Input() isStrategy:boolean=false // inject service if true *

How can I provide service depending on isStrategy Input ?

Here's an example

Hamza Haddad
  • 1,516
  • 6
  • 28
  • 48
  • Hi, not sure I understood. Are you trying to conditionally provide either `SelectionStrategy` or `FiveDayRangeSelectionStrategy` according to the `isStrategy` input? – João Ghignatti Oct 06 '22 at 05:47
  • I don't see the difference between them, but for me I should provide them both ? I don't know if only providing `selectionStrategy` will works. And yes I should provide the same behaviour depending on `isStrategy` value. if `false` do not provide service – Hamza Haddad Oct 06 '22 at 07:07
  • Hi, look here https://stackoverflow.com/questions/43450259/how-to-conditionally-inject-service-into-component – Belouccio Oct 07 '22 at 22:19

0 Answers0