如何在ES6中使用angular2 DynamicComponentLoader?

won*_*rld 4 dependency-injection angular

没有使用打字稿而是使用ES6和angular2 alpha39动态加载组件.以下代码与我在我的应用程序中的代码类似.我注意到的是angular2不会创建DynamicComponentLoaderElementRef的实例并注入构造函数.他们是未定义的.

如何使用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');
  }
}
Run Code Online (Sandbox Code Playgroud)

ale*_*ods 12

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

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

看到这个plunker

如果要在ES6中编写代码(不支持装饰器),则还必须使用静态getter作为annotations属性.在这种情况下,您必须导入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');
  }
}
Run Code Online (Sandbox Code Playgroud)

看到这个plunker