loading two components in angular2 non SPA

2020-04-18 05:46发布

问题:

Given the following components. I want to use these components on a non SPA web site exactly like the plunker here. This sample is no longer valid, as the latest beta of angular 2 uses modules, bootstrap is no longer defined, and I cannot get the two components to work in parallel.

// Our first component.

import {Component} from 'angular2/core'

@Component({
  selector: 'comp1',
  providers: [],
  template: `
    <div>
      <h3>Hello, {{name}}</h3>

    </div>
  `,
  directives: []
})
export class Comp1 {
  constructor() {
    this.name = 'I am ng2 component 1'
  }
}

// Our second component.

import {Component} from 'angular2/core'

@Component({
  selector: 'comp2',
  providers: [],
  template: `
    <div>
      <h3>Hello, {{name}}</h3>

    </div>
  `,
  directives: []
})
export class Comp2 {
  constructor() {
    this.name = 'I am ng2 component 2'
  }
}

There is a plunker here, using a beta version of angular. How do I register these two components using the latest version of angular 2. The sample is not longer valid for the newer angular versions.

When I attempt to import bootstrap, the newer versions of angular are structured differently.

import {platform} from '@angular/core';
// platform is undefined.
import { bootstrap, BROWSER_PROVIDERS, BROWSER_APP_PROVIDERS } from '@angular/platform-browser';
// bootstrap is undefined, BROWSER_PROVIDERS is undefined etc.

回答1:

The answer to anyone else attempting this, is to create two modules, and register each module separately

Registration

//main entry point
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModuleA, AppModuleB} from './app';

platformBrowserDynamic().bootstrapModule(AppModuleA);
platformBrowserDynamic().bootstrapModule(AppModuleB);

Modules

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppA ],
  bootstrap: [ AppA ]
})
export class AppModuleA {}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppB ],
  bootstrap: [ AppB ]
})
export class AppModuleB {}


回答2:

Seems you are missing a module definition e.g.:

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import {Comp1} from './comp1';
import {Comp2} from './comp2';

@NgModule({
    imports: [
        BrowserModule
    ],
    declarations: [
        Comp1,
        Comp2
    ],
    bootstrap: [Comp1]
})

export class AppModule { }

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);


标签: angular