2
export const FormatDate = new InjectionToken('FormatDate');
...
@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  providers: [{ provide: FormatDate, useValue: 'MM.yyyy' }]
})
export class DatePicker {
  @Input() format: string
  ...
}

I want to dynamically provide 'FormatDate' based on input 'format' parameter. If format === 'short' then useValue: 'MM.yy'. If format === 'long' then useValue: 'MM.yyyy'. Is that possible?

Anton Fil
  • 223
  • 2
  • 8
  • you can use a `factory` but you won't be able to use your `@Input` value. https://angular.io/api/core/FactoryProvider – Michael Desigaud Mar 24 '21 at 13:54
  • i'd step back and explain what you're actually trying to solve with this solution rather than trying to get this solution to work – bryan60 Mar 24 '21 at 14:02
  • I have component DatePicker. It hasn't been written by me initially. It has this provider { provide: FormatDate, useValue: 'MM.yyyy' }. Now I need to use this component in another place but with date format 'MM.yy'. I'm looking for the easiest fix. – Anton Fil Mar 24 '21 at 14:10
  • If your component would implement/extends FormatDate, than actually you would be able to format accordingly to the @Input value - as FormatDate you woulr provide component instance. How is that FormatDate injected and used elsewhere? – Antoniossss Mar 24 '21 at 14:38
  • This is XY problem - you ask how to do X to achieve Y while you should ask how to do Y. Here your approach is just bad I think. – Antoniossss Mar 24 '21 at 14:42

1 Answers1

0

Yes, you can do that using pipe. Create a pipe and the transform method should be like this(pseudo code might help you to create a flow):

exPipe.ts

 transform(format: any) {
     return format === 'long' ? fetch value form store or anywhere(MM.yyyy)
                              : fetch value form store or anywhere(MM.yy) || (MM.yyyy).slice(0, 4) // just slice it
  }

In the template you can do this(just an example) :

<div> {{format | exPipe }}</div>
Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
  • Thanks for reply. This 'DateFormat' is then used (injected) in another service and not in the template. – Anton Fil Mar 24 '21 at 14:40
  • Yes, this is how you should transform dynamic data on view, thats why pipes are for. You need to create a good flow so that you can take the leverage of angular framework as it provides better way to do some specific task like this using pipes. Itf this answer helped you can upvote and accept it. – Apoorva Chikara Mar 24 '21 at 14:49