简体   繁体   中英

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: 在此处输入图片说明

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. 在此处输入图片说明

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

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 ) 在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM