Home > database >  How to use PopperJs 2 with Angular 13
How to use PopperJs 2 with Angular 13

Time:03-04

I added PopperJS 2.11 as dependencie. Then I try to use Popper in AppComponent but I'm not sure how to call instance of Popper. Here is my code:

app.component.html:

<button #button>Click</button>
<div #tooltip>
    lorem ipsum
</div>

app.component.ts:

import { Component,OnInit, ViewChild} from '@angular/core';
import { createPopper, VirtualElement, Instance } from '@popperjs/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  
  @ViewChild('button') button: Element | VirtualElement;
  @ViewChild('tooltip') tooltip: HTMLElement;

    ngAfterViewInit(){
        createPopper(this.button, this.tooltip, {
            modifiers: [
              {
                name: 'offset',
                options: {
                  offset: [0, 8],
                },
              },
            ],
        });
    }
    
}

But in console I have: createPopper.js:209 Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.

CodePudding user response:

Update the problem is that you are write

**WRONG**
@ViewChild('button') button: Element | VirtualElement;
@ViewChild('tooltip') tooltip: HTMLElement;

With viewChild you get a ElementRef

  @ViewChild('bt', { static: true }) button!: ElementRef
  @ViewChild('tooltip', { static: true }) tooltip!: ElementRef

And use

this.popperInstance = Popper.createPopper(this.button.nativeElement,
             this.tooltip.nativeElement)

See a stackblitz with the first example of the tutorial

NOTE: Don't forget install @propperjs/core

npm i @popperjs/core

see stackblitz

  • Related