【问题标题】:AngularJS 2 - Reuse ComponentsAngularJS 2 - 重用组件
【发布时间】:2016-02-26 08:14:01
【问题描述】:

我在我的项目中使用AngularJS 作为模板框架。

我不想只使用Angular,还要插入一些HTML

来自Angular Tutorial

<body>
    <my-app>Loading...</my-app>
    <hr />
    <!-- Another selector but doesn't work -->
    <my-app>Loading...</my-app>
</body>

我想重用选择器,但第二次调用没有被模板替换。

有没有办法在调用之间插入不同的数据时重用组件?

我知道Angular2 是如何与全局组件和子组件一起工作的,但是有没有办法绕过它? 喜欢使用 partials 组件吗?

我知道它可以像this 那样完成。

但是,如果我想在插入不同数据的同时重复使用模板 3 次,我必须声明 3 个组件吗? 是否可以创建同一个选择器的多个实例?

【问题讨论】:

    标签: angular


    【解决方案1】:

    不支持。两次第一个标签都被寻址,第二个没有到达。你需要像https://github.com/angular/angular/issues/915这样的东西

    https://github.com/angular/angular/issues/7136
    它演示了一种解决方法http://plnkr.co/edit/O0KRZHUz5jdW40mY1EgA?p=preview

    let app = platform(BROWSER_PROVIDERS).application([BROWSER_APP_PROVIDERS]);
    
    function bootstrapWithCustomSelector(app, componentType, selector:string) {
      var bootstrapProviders = [
          provide(APP_COMPONENT_REF_PROMISE,
                  {
                    useFactory: (dynamicComponentLoader: DynamicComponentLoader, appRef: ApplicationRef,
                                 injector: Injector) => {
                      console.log('now');   
                      var ref: ComponentRef;
                      return dynamicComponentLoader.loadAsRoot(componentType, selector, injector,
                                                               () => { appRef._unloadComponent(ref); })
                          .then((componentRef) => ref = componentRef );
                    },
                    deps: [DynamicComponentLoader, ApplicationRef, Injector]
                  }),
    
      ];  
      return app.bootstrap(componentType, bootstrapProviders);
    }
    
    bootstrapWithCustomSelector(app, AppComponent, 'my-custom-app');
    

    【讨论】:

    • 如果我没记错的话,解决方法只允许重命名选择器,但我不能重用它。我仍然无法添加选择器“my-custom-app”的另一个实例。或者,是否有任何实用的方法可以将此解决方法用于我想做的事情?
    • 似乎与您想要的相反。该解决方法允许引导同一组件两次。
    • 我尝试使用此解决方法在一定程度上达到所需的结果。我使用 Input 来允许提供者返回不同的数据。我的观点有问题:plnkr.co/edit/cDrAL84k1BKMKzEG7jU6?p=preview
    • 我自己没用过。我只记得在 GitHub 上看到过讨论。我猜这个问题是由loadAsRoot 引起的,它目前已经坏了。
    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多