如何在一个页面中渲染多个angular2组件?

时间:2016-02-09 12:33:33

标签: javascript angularjs rendering angular

我正在研究这个项目,我必须在一个页面中加载多个组件。 我的目录结构是这样的: Directory Structure

我先前在angular2中创建了一些组件。 如果我更改main.ts中的组件,我可以逐个渲染所有组件 以下是main.ts的内容 1.main.ts

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Component1} from './Component1/Component1.component'
import {Component2} from './Component2/Component2.component'
import {Component3} from './Component3/Component3.component'
import {Component4} from './Component4/Component4.component'
import {Component5} from './Component5/Component5.component'

bootstrap(Component5,[
  HTTP_PROVIDERS,
]);

2.index.html

<html>

<head>
    <title>Angular 2 TypeScript App</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="iCETS">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="node_modules\bootstrap\dist\css\bootstrap.min.css" rel="stylesheet" />
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <script src="node_modules/angular2/bundles/http.dev.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
</head>

<!-- 3. Display the application -->

<body>
    <component_5>Loading...</component_5> //it works
    //what i want to achieve
    <component_1>Loading...</component_1>
    <component_2>Loading...</component_2>
    <component_3>Loading...</component_3>
    <component_4>Loading...</component_4>
</body>

</html>
有什么方法可以在一个页面中呈现所有这些组件吗?

1 个答案:

答案 0 :(得分:2)

为此,您需要引导每个组件,如下所述:

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/add/operator/map';
import {Component1} from './Component1/Component1.component'
import {Component2} from './Component2/Component2.component'
import {Component3} from './Component3/Component3.component'
import {Component4} from './Component4/Component4.component'
import {Component5} from './Component5/Component5.component'

bootstrap(Component1,[ ... ]);
(...)
bootstrap(Component5,[
  HTTP_PROVIDERS,
]);

请参阅此链接:https://angular.io/docs/ts/latest/api/platform/browser/bootstrap-function.html,部分&#34;引导多个应用程序&#34;。