所以您正在使用innerHTML 渲染动态html,并且您可能发现使用innerHTML 时角度代码不起作用。正确的?如果您在anchor 标签中使用href 属性,点击它会再次加载您的应用程序。
这可能有点矫枉过正,但您使用 RuntimeComponent。
基本上:
- 你创建了一个
RuntimeComponentModule
- 获取
ComponentFactory
- 实例化单个组件并将其宿主视图插入到您的容器中。
示例代码如下:
app.component.html
<div #container></div>
<router-outlet></router-outlet>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
private componentRef: ComponentRef<{}>;
constructor(private compiler: Compiler) { }
ngOnInit(): void {
const template = `
<h1>Check Header H1</h1>
<a [routerLink]='["/a"]'>Go to A</a>
<a [routerLink]='["/b"]'>Go to B</a>
`;
const data = [];
this.createComponent(template, data);
}
createComponent(_template, _data): any {
let metadata = {
template: _template
};
let factory = this.createComponentFactorySync(metadata, null, _data);
if(this.componentRef){
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
}
createComponentFactorySync(metadata: Component, componentClass: any, inputdata: any): ComponentFactory<any> {
const cmpClass = componentClass || class RuntimeComponent { /*Component declaration*/
name: string = "C1"; data: any = inputdata
ngOnInit(): void {
console.log('ngOnInit()')
}
ngOnDestroy(): void {
console.log('ngOnDestroy()');
}
};
const typeD: TypeDecorator = Component(metadata);
const decoratedCmp = typeD(cmpClass);
@NgModule({imports: [RouterModule], declarations: [decoratedCmp]}) /*import RouterModule for RouterLink to work*/
class RuntimeComponentModule {}
let module: ModuleWithComponentFactories<any> = this.compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
}
app.module.ts
const appRoutes:Routes = [
{ path: '', redirectTo: 'a', pathMatch:'full'},
{ path: 'a', component: AComponent},
{ path: 'b',component: BComponent},
]
注意:
- 与您不同,我已将应用程序组件的 div
#container 在运行时创建。但是,它的 html 模板中有 a [routerLink] 可以工作。
- 不要盲目复制粘贴,使用前自己研究一下。