如何在ES6中使用angular2 DynamicComponentLoader?

时间:2015-10-09 09:41:56

标签: dependency-injection angular

使用打字稿但 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');
  }
}

1 个答案:

答案 0 :(得分:12)

如果你想在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

相关问题