简体   繁体   中英

Provide additional provider in MatDialog

Imagine you have Angular service without provideIn, so it is available only in certain components and their children. Now one such component opens MatDialog -- is it possible to have that service injected there?

As I see by default Angular does not count MatDialog component as a child of caller component and also I do not see any settings to change that.

PS Service here is stateful, so just putting it to providers of MyDialogComponent will create new service, which is not desired.

All you have to do is provide the dialog.open method with ViewContainerRef where the desired service instance lives. 'VERY_IMPORTANT_SERVICE' will be available for injection in 'SomeComponent'. See the code below

@Component({
    selector: 'cmp',
    providers: [ VERY_IMPORTANT_SERVICE ]
})
export class Component {
    constructor(private dialog: MatDialog, private viewContainerRef: ViewContainerRef) {}

    openDialog() {
       this.dialog.open(SomeComponent, {
           viewContainerRef: this.viewContainerRef
       })
    }
}

If you do not provide your service into the root, then you have to provide it either in

  • An Angular feature (component, directive...)
  • An Angular module

Providing it into a feature implies that everytime that feature gets created, it gets an instance of that service.

If you provide it in the module, it implies that everytime the module is created, one instance of that service is created, which will be common for every feature in that module.

If you wish to provide the module instance to your dialog component, you can. If you choose the feature providing, then you will have a new instance of that service into your dialog component (which will be useless to keep a state from your "parent" component).

I hope it answers the question, and if not, feel free to ask for more explanation.

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