Piyush Jain
Piyush Jain

Reputation: 1986

How to use Angular 2 component in Angular 1 app using @angular/upgrade

This question might be duplicate but I have tried all possible options.

I am trying to use my Angular 2 component in Angular 1 app using @angular/upgrade.

angular2 files :-

simple hello component in app/components/hello.

hello.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.scss']
})
export class HelloComponent implements OnInit {

  constructor() { 
  }

  ngOnInit() {
  }

}

hello.component.html

<p>
  hello works!
</p>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { UpgradeModule } from '@angular/upgrade/static';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloComponent } from './components/hello/hello.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloComponent
  ],
  imports: [
    BrowserModule,
    UpgradeModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [
    HelloComponent
  ]
})
export class AppModule { 
  constructor(private upgrade: UpgradeModule) { }
  ngDoBootstrap() {
    this.upgrade.bootstrap(document.body, ['usr']);
  }
}

platformBrowserDynamic().bootstrapModule(AppModule);

In my Angular 1 app :- app.ts (root file)

import { HelloComponent } from '../angular/src/app/components/hello/hello.component';
import { downgradeComponent } from './node_modules/@angular/upgrade/static/static'

let moduleList = ['ngCookies', 'ngSanitize','$rootScope', '$locationProvider '];
angular.bootstrap(document.body, ['usr']);

let app: any = angular.module('usr', moduleList)
.directive(
    'appHello',
    downgradeComponent({ component: HelloComponent })
  );

index.html of Angular 1 (I have added base href and root which is default component of angular, app-root component is rendering properly in my angular 1 app)

<base href="/">
<app-root></app-root>

header.html (angular 1 header component where I want to show my angular 2 hello component)

<app-hello></app-hello>

screenshots. Angular 2 root component rendering properly in Angular 1 app Angular 2 hello component is not rendering properly in Angular 1 app

Thanks in advance.

Upvotes: 1

Views: 226

Answers (1)

user733421
user733421

Reputation: 497

https://angular.io/api/upgrade/static/downgradeModule says

You cannot use downgradeModule() and UpgradeModule in the same hybrid application. Use one or the other.

This means you can only use downgrade module while bootstrapping NG1

Upvotes: 1

Related Questions