简体   繁体   中英

Angular 6 + Popper.js (without jQuery)

I am trying to setup Popper.js to work with angular 5, without bootstrap or jquery. I tried following this https://github.com/FezVrasta/popper.js/#react-vuejs-angular-angularjs-emberjs-etc-integration , but it is not exactly a point A to B description for angular applications.

I installed Popper.js via npm

npm install popper.js --save

then I chose to bundle the esm module to my angular-cli scripts

"scripts": [
                   (...)
        "../node_modules/popper.js/dist/esm/popper.js"
      ],

Since esm/popper.js exports Popper variable as follows.

var Popper = function () {

I figured that I would just declare the popper variable in my angular template like this

declare var Popper;

Alas, I had no luck with it.

在此输入图像描述

Does anybody have ideas on how to correctly implement this?

First I installed Popper.js with npm

npm install popper.js --save

Then I defined Popper as an external script in angular-cli.json

angular-cli.json

"scripts": [
                   (...)
        "../node_modules/popper.js/dist/esm/popper.min.js"
      ],

Then I import popper inside the angular component, initialize it the correct Angular way and we are good to go.

Component

import Popper, {PopperOptions} from 'popper.js';

@Component({
               selector: 'x',
               templateUrl: './x',
               styleUrls: ['./x']
           })
export class X_Component implements OnInit {
    @Input() popperOptions: PopperOptions = {};
    @Input() popperTarget: string | Element;
    private popper: Popper;

    constructor(private el: ElementRef) { }

    ngOnInit() {
        this.popper = new Popper(
            this.getTargetNode(),
            this.el.nativeElement,
            this.popperOptions
        );
    }

    private getTargetNode(): Element {
        if (this.popperTarget) {
            if (typeof this.popperTarget === 'string') {
                return document.querySelector(this.popperTarget);
            } else {
                return this.popperTarget;
            }
        } else {
            return this.el.nativeElement;
        } 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM