在 Angular2 中你应该使用动态组件加载器 https://angular.io/docs/js/latest/api/core/DynamicComponentLoader-class.html在页面上插入一些“编译内容”。例如,如果你想编译下一个 html:
<div>
<p>Common HTML tag</p>
<angular2-component>Some angular2 component</angular2-component>
</div>
然后你需要用这个 html 作为模板创建组件(我们称之为CompiledComponent
)并使用DynamicComponentLoader
将此组件插入页面上。
@Component({
selector: 'compiled-component'
})
@View({
directives: [Angular2Component],
template: `
<div>
<p>Common HTML tag</p>
<angular2-component>Angular 2 component</angular2-component>
</div>
`
})
class CompiledComponent {
}
@Component({
selector: 'app'
})
@View({
template: `
<h2>Before container</h2>
<div #container></div>
<h2>After conainer</h2>
`
})
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
查看这个笨蛋 http://plnkr.co/edit/SvhzsaAx7kvH245wDfmb?p=preview
UPD您可以在之前动态创建组件loader.loadIntoLocation()
call:
// ... annotations
class App {
constructor(loader: DynamicComponentLoader, elementRef: ElementRef) {
// template generation
const generatedTemplate = `<b>${Math.random()}</b>`;
@Component({ selector: 'compiled-component' })
@View({ template: generatedTemplate })
class CompiledComponent {};
loader.loadIntoLocation(CompiledComponent, elementRef, 'container');
}
}
我个人不喜欢它,对我来说它看起来像是一个肮脏的黑客。但这里是笨蛋 http://plnkr.co/edit/YYyMwVAakktn2FoVhKN4?p=preview
PS请注意,此时 angular2 正在积极开发中。所以情况随时可能改变。