【发布时间】:2019-04-04 14:11:30
【问题描述】:
我有一个组件,我想在其中包含多个 HTML 文件, 我正在使用 Angular 4,我想同时加载所有 HTML 文件。
我检查并发现使用 directive 可以做到这一点,但我无法看到一个示例。
有人可以推荐使用什么以及如何做到这一点吗?
我试过了,它不能正常工作:
import {
Compiler, Component, Injector, VERSION, ViewChild, NgModule, NgModuleRef,
ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';
@Component({
selector: 'mainComponent',
template: `
<ng-container #dynamicTemplate></ng-container>
`
// or with a templateUrl
})
export class MainComponent implements AfterViewInit {
@ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;
constructor(private _compiler: Compiler,
private _injector: Injector,
private _m: NgModuleRef<any>) {
}
ngAfterViewInit() {
let myTemplateUrl = '../first.component.html';
//myTemplateUrl = './another-template.component.html';
const tmpCmp = Component({
moduleId: module.id, templateUrl: myTemplateUrl
})(class {
});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {
});
this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = f.create(this._injector, [], null, this._m);
cmpRef.instance.name = 'dynamic';
this.dynamicTemplate.insert(cmpRef.hostView);
});
}
}
【问题讨论】:
-
请在 stackblitz 中分享至少最少的代码或工作演示,以便其他人可以了解到目前为止已经尝试过的内容以及需要更改的内容。您检查了吗?
<p [innerHTML]='bindWhatYouWantShow'></p> -
@worstCoder 我已经添加了我的代码