-1

我添加了 PopperJS 2.11 作为依赖项。然后我尝试在 AppComponent 中使用 Popper,但我不确定如何调用 Popper 的实例。这是我的代码:

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],
                },
              },
            ],
        });
    }
    
}

但在控制台中我有:createPopper.js:209 Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.

4

1 回答 1

0

更新问题是你在写

**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

stackblitz

于 2022-03-03T17:12:31.757 回答