最近在做Angular2 的预研工作,需要动态添加组件,并渲染出组件显示效果。查阅了一此资料,分享如下:
http://stackoverflow.com/questions/34784778/equivalent-of-compile-in-angular-2
import {Component, DynamicComponentLoader, ElementRef, OnInit} from 'angular2/core'
function compileToComponent(template, directives) {
@Component({
selector: 'fake',
template , directives
})
class FakeComponent {};
return FakeComponent;
}
@Component({
selector: 'hello',
template: '<h1>Hello, Angular!</h1>'
})
class Hello {}
@Component({
selector: 'my-app',
template: '<div #container></div>',
})
export class App implements OnInit {
constructor(
private loader: DynamicComponentLoader,
private elementRef: ElementRef,
) {}
ngOnInit() {} {
const someDynamicHtml = `<hello></hello><h2>${Date.now()}</h2>`;
this.loader.loadIntoLocation(
compileToComponent(someDynamicHtml, [Hello])
this.elementRef,
'container'
);
}
}
http://www.talkinghightech.com/en/dynamically-rendering-components-angular2/
热门评论
DynamicComponentLoader 这个AP现在好像被移除了