[英]How to use angular2 DynamicComponentLoader in ES6?
我沒有使用打字稿而是使用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中編寫代碼,我認為目前最簡潔的注入方法是使用靜態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');
}
}
如果要在ES6中編寫代碼(不支持裝飾器),則還必須使用靜態getter作為annotations
屬性。 在這種情況下,您必須導入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');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.