Error: NullInjector - The injector encountered an error when trying to inject the Component into the MatDialogRef in the AppModule

When utilizing a component via routing as well as injecting it as the "target" of a modal dialog, I encountered an issue:

export class Component1 implements OnInit {
constructor(private service: <someService>,
public dialogRef: MatDialogRef<Component1>, //These 2 lines are used as 
                                            //injection from the opener
@Inject(MAT_DIALOG_DATA) public data: any) {}

Here is the code of the "opener":

openComponent1aSModalPage()
{
  Const dialogRef = this.dialog.open(Component1, {
  width: '70%',
  height: '70%',
  data: {property: propertyValue}
 });

While it works when I trigger the opener, attempting to access the same component via regular routing results in:

Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[Component1 -> MatDialogRef]: StaticInjectorError(Platform: core)[Component1-> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!

How can I modify the component to function in both scenarios?

Answer №1

I successfully implemented a workaround for the optionally injected parameters within the component: By using the @Optional() decorator before the constructor parameter, I ensured that it would only be injected if a provider was registered.

constructor(private service: <someService>,
@Optional() public dialogRef: MatDialogRef<Component1>,
@Optional() @Inject(MAT_DIALOG_DATA) public data: any )

This solution was discovered through the following resource: DI constructor with optional parameters

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

Limit the elements in an array within a specified range of dates

Currently, I am working on implementing a filter functionality for a data array used in a LineChart within my Angular application using TypeScript. The structure of the data array is as follows: var multi = [ { "name": "test1", "series": [ ...

Modify the size of HTML elements when a button is clicked using Angular

Check out this code snippet I wrote: <div> <p>First</p> <p>Second</p> <div> <p>Third</p> <p>Fourth</p> </div> <button>+</button> <button>+</button> I'm trying t ...

Guide to typing a new version of a function without any optional parameters using a mapped tuple

I am attempting to create a modified version of a function that has the same arguments as the original function, but with none being optional. I have tried using a mapped tuple approach with the following logic: type IFArgs = ArgsN<typeof getFunc> t ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

ejs-lineargauge major divisions and minor divisions centered

I've been trying to align majorTicks and minorTicks in the middle of the axis, but so far I haven't found a solution despite searching and googling extensively. Here's a snippet of my code: majorTicks: { height: 12, interval: 1, width ...

What are the limitations of using useState with complex nested objects and arrays in React components?

In my scenario, I am working with an array of characters. Each character contains multiple builds, and each build includes a string for weapons and a string for artifacts. I am developing a tool to extract specific portions of these strings and assign them ...

Angular 16 brings a revolution in routerLink behavior

Previously, when I was using angular < 16, my routes configuration looked like this: { path: Section.Security, canActivate: [AuthGuard, AccessGuard, AdminGuard], children: [ { path: '', pathMatch: 'full', ...

Struggling to get the Okta Auth0's AuthGuard to properly redirect to a specific route following a successful login request for a protected route

I have implemented Auth0 in my Angular application to authenticate users using the steps outlined below: Users visit the root page (e.g. ) and click on the Login button via their Google account. Users are redirected to the Auth0 login page through the Goo ...

403 Error: Access Denied for Spring Cloud Gateway

Scenario In the development of my project, I have opted for a MicroServices architecture. Specifically, I am utilizing Angular 15 for the Frontend and Spring 3.0.2 as the Backend technology. To manage authentication for both the frontend and backend, I ha ...

There was a parsing error due to encountering an unexpected reserved word 'interface' in the code, as flagged

I'm encountering an issue with my code when trying to utilize Props. The error message I'm receiving is "Parsing error: Unexpected reserved word 'interface'. (3:0)eslint". This project is being developed using next with TypeScript. Er ...

What are the guidelines for utilizing square brackets [ ] in directives like @Inputs?

I'm feeling a bit lost. Check out this straightforward directive: @Directive({ selector: '[myDirective]' }) export class MyDirective { private textContent: string; private isEnabled: boolean; @Input() myD ...

What is the process for initiating an Angular 2 Materialize component?

I'm new to using angular2 materialize and I've found that the CSS components work perfectly fine. However, I'm facing an issue when it comes to initializing components like 'select'. I'm unsure of how or where to do this initi ...

Is there a way to alter the stroke color of an SVG icon in Angular 2 or 4 by clicking on it?

Having trouble with this code, can someone provide a solution? This is the SVG icon code: <svg id="Home" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52.28 43.49"> <defs> <style> .cls-1{fill:none;stro ...

Utilize TypeScript function types in React for enhanced functionality

I have made the decision to refactor a project that was originally created with vanilla JavaScript and now I want to transition it to TypeScript. One issue I am facing is how to pass a function as a type on an interface. Although I referred to the TypeScr ...

Exploring ways to incorporate the context value into my component's functionality

Hi, I'm new to TypeScript and I'm facing an issue when trying to use a value I created in my context API. I keep getting the error message "Property 'sidebar' does not exist on type 'IStateContext | null'", even though it exis ...

transferring attributes from a higher component to a lower one (modal)

https://i.sstatic.net/tSXb5.png https://i.sstatic.net/H4xmj.png I am relatively new to React and I want to share a detailed problem description: I have a Todo project that consists of multiple interfaces. The main interface displays all the lists, each ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Using Angular to create an Echarts timeline that showcases 3 distinct categories

Here is an example graph created with Highcharts Struggling to replicate a chart like this using Echarts and ngx-echarts. Has anyone encountered this issue before? Currently utilizing the following dependencies: "@angular/animations": "^17 ...

The success of an Angular function hinges on the outcome of an asynchronous function

Scenario: In my code, I have a function named isAuthorized() in a singleton called AuthSessionSingleton. This function depends on the result of an asynchronous operation. The async operation is an API call triggered in the constructor, expecting an objec ...