如何解决如何在 Angular 的根组件中添加模板?
我想在我的 Angular 应用程序中独立于用户当前所在的组件播放背景音乐。为此,我需要在根组件中创建动态组件(musicComponent),而不是在用户单击按钮以激活音乐的子组件中。
@ViewChild('m',{static : false,read: ViewContainerRef }) musicentry: ViewContainerRef;
ngAfterViewInit(){
const factory = this.resolver.resolveComponentFactory(BackgroundMusicComponent);
this.MusicComponentRef = this.musicentry.createComponent(factory);
}
模板:
<template #m></template>
不幸的是,如果模板在子组件中,FactoryResolver 可以工作,但如果模板在根组件 (app.component.html) 中,则不能工作。
您对如何在根组件中创建组件有任何想法吗?谢谢!
解决方法
您说的是动态组件。你可以试试这个
<ng-template appAdHost></ng-template>
在页面上
@ViewChild(AdHostDirective) dlHost: AdHostDirective;
constructor(private cfr: ComponentFactoryResolver) {
}
ngAfterViewInit() {
this.dlHost.viewContainerRef.createComponent(
this.cfr.resolveComponentFactory(DyTwoComponent)
);
}
逻辑
{{1}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。