【问题标题】:How to use Angular 2 component in Angular 1 app using @angular/upgrade如何使用 @angular/upgrade 在 Angular 1 应用程序中使用 Angular 2 组件
【发布时间】:2020-01-11 21:12:17
【问题描述】:

这个问题可能是重复的,但我已经尝试了所有可能的选项。

我正在尝试使用 @angular/upgrade 在 Angular 1 应用程序中使用我的 Angular 2 组件。

angular2 文件:-

app/components/hello 中的简单 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);

在我的 Angular 1 应用程序中:- app.ts(根文件)

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 })
  );

Angular 1 的 index.html(我添加了 base href 和 root,这是 angular 的默认组件,app-root 组件在我的 angular 1 应用程序中正确呈现)

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

header.html(我想在其中显示我的 angular 2 hello 组件的 angular 1 标头组件)

<app-hello></app-hello>

截图。

提前致谢。

【问题讨论】:

    标签: angularjs angular angular-upgrade angular-hybrid


    【解决方案1】:

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

    你不能在同一个混合中使用 downgradeModule() 和 UpgradeModule 应用。使用其中一种。

    这意味着您只能在引导 NG1 时使用降级模块

    【讨论】:

    • 我使用的是downgradeComponent 而不是downgradeModule()
    • 你是对的(我的错)。我可以看到您正在手动引导和自动引导。尝试删除引导程序:[AppComponent],
    • 我已经从 app.module.ts 中删除了 this.upgrade.bootstrap(document.body, ['usr']);,即使这样也无法正常工作,但是当我在根组件中添加 hello 组件时,它可以正常呈现。
    • 你不能删除 this.upgrade.bootstrap(document.body, ['usr']);因为这是引导 ng1 的原因,它是您需要删除的另一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2017-01-12
    相关资源
    最近更新 更多