John F.
John F.

Reputation: 67

How to add in Angular a template in the Root Component?

I want to play background music in my Angular app independent from the component in which the user is currently. For that I need to create dinamically a component(musicComponent) in the Root Component and not in the child component where the User clicks the button in order to activate music.

@ViewChild('m', {static : false, read: ViewContainerRef }) musicentry: ViewContainerRef;


ngAfterViewInit(){
const factory = this.resolver.resolveComponentFactory(BackgroundMusicComponent);
this.MusicComponentRef = this.musicentry.createComponent(factory);

}

Template:

<template #m></template>

Unfortunately FactoryResolver works if the template is inside the child component but not if the template is in the Root component (app.component.html).

Do you have any ideas how I can create the component in the Root Component? Thank you!

Upvotes: 1

Views: 813

Answers (1)

vueAng
vueAng

Reputation: 453

You're talking about dynamic components. You can try this

@Directive({
  selector: '[appAdHost]'
})
export class AdHostDirective {

  constructor(public viewContainerRef:ViewContainerRef) { }
}

On the page

<ng-template appAdHost></ng-template>

logic

  @ViewChild(AdHostDirective) dlHost: AdHostDirective;

  constructor(private cfr: ComponentFactoryResolver) {
  }

  ngAfterViewInit() {
    this.dlHost.viewContainerRef.createComponent(
      this.cfr.resolveComponentFactory(DyTwoComponent)
    );
  }

Upvotes: 1

Related Questions