Angular 4: Dynamically add provider in NgModule providers array

Viewed 841

Application Background: My application is built up using ASP.net MVC(.net framework 4.6) and several Angular 4 mini SPAs

One of SPA use this approach to bootstrap components. In short this SPA could bootstrap multiple components managed by one Angular app.

Question I want to add a provider (dynamically if that is correct word) in providers array only when a component is present in html view. Hope you guys could help?

Example I want to add { provide: APP_BASE_HREF, useValue: '/shoppingbasket/my' } in providers array when AddProductToShoppingBasketComponent is loaded/present in view

Code

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ComponentFactoryResolver, ApplicationRef, Type } from '@angular/core';
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
//import { APP_BASE_HREF } from "@angular/common";

import { ToastrModule } from "ngx-toastr";
import { NgProgressModule, NgProgressInterceptor } from 'ngx-progressbar';

import { ShoppingModule } from './shopping/shopping.module';
import { SharedModule } from './shared/shared.module';
import { CheckoutModule } from './checkout/checkout.module';

import { AppRoutingModule } from './app-routing.module';


import { AppComponent } from './app.component';
import { ShoppingBasketComponent } from "./shopping/shopping-basket.component";
import { AddProductToShoppingBasketComponent } from './shopping/add-product-to-shopping-basket.component';

const components = [AppComponent, AddProductToShoppingBasketComponent, ShoppingBasketComponent];

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        SharedModule,
        CheckoutModule,
        AppRoutingModule,
        BrowserModule,
        ShoppingModule,
        NgProgressModule,
        BrowserAnimationsModule,
        ToastrModule.forRoot({
            timeOut: 5000,
            positionClass: 'toast-bottom-right',
            preventDuplicates: true,
            closeButton: true
        })
    ],
    providers: [
        //{ provide: APP_BASE_HREF, useValue: '/shoppingbasket/my' },
        { provide: HTTP_INTERCEPTORS, useClass: NgProgressInterceptor, multi: true }
    ],
    entryComponents: components
})
export class AppModule {
    //Reference: https://blog.novatec-gmbh.de/angular-2-in-a-multi-page-application/
    constructor(private resolver: ComponentFactoryResolver) { }
    ngDoBootstrap(appRef: ApplicationRef) {
        components.forEach((componentDef: Type<{}>) => {
            const factory = this.resolver.resolveComponentFactory(componentDef);
            if (document.querySelector(factory.selector)) {
                appRef.bootstrap(factory);
            }
        });
    }
}
0 Answers
Related