Angular providers: Provide value dynamically based on @Input() parameter

Viewed 253
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?

1 Answers

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>
Related