【问题标题】:Angular 2: how to load separate, unrelated components on to a pageAngular 2:如何将单独的、不相关的组件加载到页面上
【发布时间】:2016-03-28 17:50:10
【问题描述】:

我在一个页面上有两个完全不相关的组件。我不想将它们作为子组件加载到父模板下。我如何将它们都加载到一个页面上?

<section>
<h1>Heading</h1>
<the-first-component></the-first-component>
</section>

(lots of html)

<main>
<h1>Another heading</h1>
<the-second-component></the-second-component>
</main>

(lot more html)

【问题讨论】:

    标签: angular


    【解决方案1】:

    只需为每个组件调用bootstrap

    bootstrap(AppComponent1, [ /* providers here */]);
    bootstrap(AppComponent2, [ /* providers here */]);
    

    如果您想共享数据,例如可以使用共享服务

    @Injectable()
    class MySharedService {
    }
    
    var shared = new MySharedService();
    
    bootstrap(AppComponent1, [provide(MySharedService, {useValue: shared}]);
    bootstrap(AppComponent2, [provide(MySharedService, {useValue: shared}]);
    

    这样,当AppComponentx 或其子组件之一或另一个服务具有类似的构造函数参数时

    constructor(private myShared: MySharedService) {}
    

    那么您在任何地方都可以使用相同的全局实例,以便能够轻松地在您页面上的不同 Angular2“应用程序”之间进行通信。 另见detect change of nested property for component input

    【讨论】:

    • 如果我在所有组件上调用 bootstrap 并且它们不在页面上,我会收到错误消息。有什么办法可以避免这种情况?我的目标是在页面上嵌入多个可重用的组件
    猜你喜欢
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    相关资源
    最近更新 更多