我不是使用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');
}
}
如果你想在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');
}
}
见此柱塞
如果你想在不支持装饰器的ES6中编写代码,你还必须为annotations
属性使用静态getter。在这种情况下,必须导入ComponentMetadata
和ViewMetadata
,而不是Component
和View
。例如:
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');
}
}
见此柱塞