Csibi Norbert
Csibi Norbert

Reputation: 930

Component does not create dynamically to div specified using ViewChild in Angular

I'm trying to append/create into a specific div a component. However, the component is being created but not where I would like it to be. What I'm doing wrong?

enter image description here

I would like the k-sidebar component to be inside the div I'm showing into the image.

Below is my code.

App.component

 import { Component, OnInit, OnDestroy, ViewChild, ElementRef, Renderer2, ViewContainerRef, 
 ComponentFactoryResolver, ComponentRef, ComponentFactory} from '@angular/core';
 @Component({
  selector: 'app-comp',
  templateUrl: './app-comp.component.html',
  encapsulation: ViewEncapsulation.None
 })
 export class AppComponent implements OnInit {
  componentRef: any;
  @ViewChild('dynamicSidebar', {read: ViewContainerRef})
  public dynamicSidebar: ViewContainerRef;

  constructor(private factoryResolver: ComponentFactoryResolver,
   private containerRef: ViewContainerRef) { }

  ngOnInit() {
   this.createSidebarComp();
 }


 createSidebarComp(){
  this.containerRef.clear();
  this.containerRef.createComponent(this.factoryResolver.resolveComponentFactory(KSideBarComponent));
 }
}

HTML

<!-- header test -->
<k-header [navItems]="navItems" [title]="title">
 <ng-template rightSection>
 <k-icon [icon]="testIcon"></k-icon>
</ng-template>
</k-header>
<!-- /header test -->

<div class="container-fluid">
 <div #dynamicSidebar></div>
 <h1>{{title}} app is running!</h1>
 <router-outlet></router-outlet>

</div>

The sidebar is inside the router-outlet, and I would like to create the component above the h1 tag based on a boolean. What I`m doing wrong?

Upvotes: 0

Views: 446

Answers (1)

saivishnu tammineni
saivishnu tammineni

Reputation: 1252

You can do

createSideBarComp() {
     this.dynamicSidebar.createComponent(this.factoryResolver.resolveComponentFactory(KSideBarComponent));
}

the problem is you are not attaching to the sidebar reference you have taken (dynamicSideBar). But you are trying to attach to a viewContainerRef injected for the component through the constructor. This is not where you want to create the component.

Upvotes: 0

Related Questions