【问题标题】:How to use angular2 DynamicComponentLoader in ES6?如何在 ES6 中使用 angular2 DynamicComponentLoader?
【发布时间】:2016-01-07 04:55:51
【问题描述】:

不是使用 typescript 而是 ES6 和 angular2 alpha39 来动态加载组件。以下代码类似于我在我的应用程序中的代码。我注意到的是 angular2 没有创建 DynamicComponentLoader 的实例,也没有创建 ElementRef 并注入到构造函数中。它们是未定义的。

如何使用 ES6 和 angular2 alpha39 进行 DynamicComponentLoader 的注入?

import {Component, View, Inject, DynamicComponentLoader, ElementRef } from 'angular2/angular2'

@Component({
  selector: 'dc',
  bindings: [ DynamicComponentLoader ]
})
@View({
  template: '<b>Some template</b>'
})

class DynamicComponent {}

@Component({
  selector: 'my-app'
})
@View({
  template: '<div #container></div>'
})
@Inject(DynamicComponentLoader)
@Inject(ElementRef)
export class App {
  constructor(
    dynamicComponentLoader, 
    elementRef
  ) {
    dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
  }
}

【问题讨论】:

    标签: dependency-injection angular


    【解决方案1】:

    如果你想在ES7中写代码,我认为此时指定注入最简洁的方法是使用parameters的静态getter:

    import {Component, View, DynamicComponentLoader, ElementRef } from 'angular2/angular2'
    
    @Component({
      selector: 'my-app'
    })
    @View({
      template: '<div #container></b>'
    })
    export class App {
    
      static get parameters() {
        return [[DynamicComponentLoader], [ElementRef]];  
      }
    
      constructor(dynamicComponentLoader, elementRef) {
        dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
      }
    }
    

    this plunker

    如果你想在不支持装饰器的 ES6 中编写代码,你还必须对 annotations 属性使用静态 getter。在这种情况下,您必须导入 ComponentMetadataViewMetadata 而不是 ComponentView 例如:

    import {ComponentMetadata, ViewMetadata, DynamicComponentLoader, ElementRef } from 'angular2/angular2';
    
    export class App {
    
      static get annotations() {
        return [
          new ComponentMetadata({
            selector: 'app'
          }),
          new ViewMetadata({
            template: '<div #container></b>'
          })
        ];
      }
    
      static get parameters() {
        return [[DynamicComponentLoader],[ElementRef]];  
      }
    
      constructor(dynamicComponentLoader, elementRef) {
        dynamicComponentLoader.loadIntoLocation(DynamicComponent, elementRef, 'container');
      }
    }
    

    this plunker

    【讨论】:

    • 救命稻草,但现在装饰器正在为@Component工作
    猜你喜欢
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 2017-02-02
    • 2020-11-10
    相关资源
    最近更新 更多