0

I have the function that I need to inject in any component:

export const matDialogCallbacks = (dialog: MatDialog, document: Document, renderer: Renderer2) => {
    dialog.afterOpened.subscribe(() => renderer.addClass(document.body, 'overflow-hidden'));
    dialog.afterAllClosed.subscribe(() => renderer.removeClass(document.body, 'overflow-hidden'));
};

I need to inject it and use:

 constructor(private matDialogCallbacks: matDialogCallbacks, private dialog: MatDialog) {
    matDialogCallbacks(dialog);
}

How to do that?

I made the service:

import { Injectable, Inject, Renderer2 } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DOCUMENT } from '@angular/common';

@Injectable({
    providedIn: 'root',
})
export class DialogEventsService {
    constructor(@Inject(DOCUMENT) private document: Document, private renderer: Renderer2) {}

    init(dialog: MatDialog) {
        dialog.afterOpened.subscribe(() => this.renderer.addClass(this.document.body, 'overflow-hidden'));
        dialog.afterAllClosed.subscribe(() => this.renderer.removeClass(this.document.body, 'overflow-hidden'));
    }
}

When I try to use this service in component I get this:

NullInjectorError: R3InjectorError(OrdersDistributionModule)[DialogEventsService -> DialogEventsService -> Renderer2 -> Renderer2 -> Renderer2]: 
meblum
  • 1,654
  • 12
  • 23

1 Answers1

1

Define the function type:

type dialogCB= (dialog: MatDialog, document: Document, renderer: Renderer2) => void

and now the function:

export const matDialogCallbacks :dialogCB = (dialog: MatDialog, document: Document, renderer: Renderer2) => {

      dialog.afterOpened.subscribe(() => renderer.addClass(document.body, 'overflow-hidden'));

      dialog.afterAllClosed.subscribe(() => renderer.removeClass(document.body, 'overflow-hidden'));
};

now create a token:

import { InjectionToken } from '@angular/core';

export const TOKEN_NAME = new InjectionToken<dialogCB>('dialog callback');

now provide it in the root module:

providers: [{ provide: TOKEN_NAME, useValue: matDialogCallbacks  }]

And finally you can inject it:

constructor(@Inject(TOKEN_NAME) private matDialogCallbacks: dialogCB, private dialog: MatDialog) {
matDialogCallbacks(dialog);

}

meblum
  • 1,654
  • 12
  • 23