Issue
Facing an issue with standalone components using Material dialog.
Here's the flow:
- Standalone Component A: Injects and uses SomeService.
- Standalone Component A opens Material Dialog:
- Dialog component (Component B) also uses SomeService.
Expected: All components (A and B) should access the same SomeService instance. Actual: Previously both components were imported on one module with provided service. After migrating to standalone components, SomeService appears to have different instances in each component. It is provided in both components. Gives error if I don't provide it in dialog component.
Tried different ways to fix this with no success.
Solution
This fixed my issue.
- Inject ViewContainerRef into your host component: In the component
that opens the dialog (Component A), you need to inject
ViewContainerRef. This is typically done in the constructor of the
component. - Modify the open method: When opening the dialog using MatDialog, pass the viewContainerRef property within the MatDialogConfig object. This step links the dialog component's (Component B) change detection and dependency injection to that of the host component.
- Remove redundant providers: Since the same instance of SomeService is now available in both components, you do not need to provide it again in the dialog component (Component B).
Answered By - Muhammad-Ali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.