angularangular-materialangular-providers

Unique provider value for child component


I am trying to create a reusable date picker component. One of the features is that you can choose a periodLevel. Such as monthly daily or yearly. The problem I have is that when I call this component from a parent component I manipulate the period level using a dateFormats variable that I put in useValue in providers. In the stackblitz I have recreated the situation and I call child1 component twice, once with a daily level and once with a monthly level: enter image description here

Both date pickers appear with a monthly level (mm/yyyy), because the dateFormats variable is adjusted in such a way for the second child component.

Inside child1 component. I use the dateFormats variable in the providers of the component to manipulate the date formatting. enter image description here

The problem is that I don't know how I can use a local variable inside useValue to avoid reusing the same dateFormats for all child components. Desired result for the stackblitz example is that the first child component shows a daily level (dd/mm/yyyy) and the second child component shows monthly level (mm/yyyy).

https://stackblitz.com/edit/angular-ivy-qpa9x6?file=src/app/app.component.html


Solution

  • Managed to solve my issue by making two adjustments.

    1. use useFactory to generate a unique instance of the dateFormats variable (abstracted away in the DataService) enter image description here

    2. Inject MAT_DATE_FORMATS into a local variable in the contructor of the component to be able to modify it --> this.thisDateFormat.

    enter image description here

    I can recommend the Angular University lesson on providers to anyone struggling with a similar issue: https://angular-university.io/lesson/angular-di-providers-injection-tokens