Search code examples
angularng-upgrade

NgModules not working with NgUpgrade


Angular 1 & 2 (RC5) application running in hybrid mode using ng-upgrade. Attempt to use @NgModule which doesn't work, I still have to add providers manually using:

 upgradeAdapter.addProvider(REACTIVE_FORM_PROVIDERS);

This is preventing me from upgrading from RC5->RC6. To use external components, I still have to add them to the directives: array for the specific component they're being used in.

import { AlertComponent } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
    selector: 'sb-staff-dashboard',
    templateUrl: 'staff-dashboard.component.html',
    styleUrls: ['staff-dashboard.component.scss'],
    directives: [ AlertComponent ]
})

Here is my relevant bootstrap code.

upgradeAdapter.addProvider(COMMON_PROVIDERS);
upgradeAdapter.addProvider(HTTP_PROVIDERS);
upgradeAdapter.addProvider(DragulaService);
upgradeAdapter.addProvider(REACTIVE_FORM_PROVIDERS);
upgradeAdapter.bootstrap(document.documentElement, ['common', CommonModule], { strictDi: true });

upgradeAdapter.ts

import {UpgradeAdapter} from '@angular/upgrade';

export const upgradeAdapter = new UpgradeAdapter();

common.module.ts

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from "@angular/forms";
import { HttpModule } from '@angular/http';
import { BrowserModule } from '@angular/platform-browser';
import { Ng2BootstrapModule } from 'ng2-bootstrap/ng2-bootstrap';
import { Dragula, DragulaService } from 'ng2-dragula/ng2-dragula';

@NgModule({
    imports: [
        BrowserModule,
        ReactiveFormsModule,
        Ng2BootstrapModule,
        HttpModule
    ],
    declarations: [
        COMMON_COMPONENTS,
        Dragula
    ],
    providers: [
        COMMON_PROVIDERS,
        DragulaService
    ]
})
export class CommonModule { }

Solution

  • You have to create the UpgradeAdapter with the module you want.

    For example:

    import { forwardRef } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { UpgradeAdapter } from '@angular/upgrade';
    
    export const upgradeAdapter = new UpgradeAdapter(forwardRef(() => CommonModule));
    

    Also, instead of importing COMMON_COMPONENTS and COMMON_PROVIDERS you have to use:

    import { CommonModule } from '@angular/common';
    
    @NgModule({imports: [CommonModule, ...]})