Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ViewContainerRef.createComponent() inside the current component

Tags:

angular

I am using the ViewContainerRef to add a component to my current component. But doing vrc.createComponent() adds the new component at the same level in the dom hierarchy as the component from which I call this function. How do I make it so that the new component is inserted inside the current one.

Code snippet

import { Component, OnInit, Input, ViewChild, ViewContainerRef } from '@angular/core';
import { TooltipComponent } from './tooltip.component';

@Component({
  selector: 'tooltip-wrapper',
  template: `
    <div class="wrapper"
        (mouseenter)="onMouseEnter()"
        (mouseleave)="onMouseLeave()">
        Hover on this
    </div>
  `
})
export class TooltipWrapperComponent implements OnInit {

  @Input() theme: 'light' | 'dark' = 'light';
  
  constructor(public vrc: ViewContainerRef) { }

  onMouseEnter() {
    this.vrc.clear();
    let tooltipRef = this.vrc.createComponent(TooltipComponent);
  }

  onMouseLeave() {
    console.log("mouse left");
    this.vrc.clear();
  }

}

like image 444
Ashutosh Shinde Avatar asked Apr 09 '26 13:04

Ashutosh Shinde


1 Answers

You can inject viewChild's container ref and call its methods instead

<div #placeToRender></div>
@ViewChild('placeToRender', {read: ViewContainerRef}) placeToRender: ViewContainerRef;

onMouseEnter() {
  this.placeToRender.clear();
  let tooltipRef = this.placeToRender.createComponent(TooltipComponent);
}

like image 101
Andrei Avatar answered Apr 11 '26 02:04

Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!