Как использовать PopperJs 2 с Angular 13

Я добавил PopperJS 2.11 в качестве зависимости. Затем я пытаюсь использовать Popper в AppComponent, но не знаю, как вызвать экземпляр Popper. Вот мой код:

приложение.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],
                },
              },
            ],
        });
    }
    
}

Но в консоли у меня есть: createPopper.js:209 Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.

1 ответ

Обновите , проблема в том, что вы пишете

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

С viewChild вы получаете ElementRef

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

И использовать

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

См. stackblitz с первым примером учебника

ПРИМЕЧАНИЕ. Не забудьте установить @propperjs/core

      npm i @popperjs/core

см. стекблиц

Другие вопросы по тегам