Angular 6 + Popper.js (without jQuery)

家住魔仙堡 提交于 2019-12-10 18:03:53

问题


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?


回答1:


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;
        } 
    }
}


来源:https://stackoverflow.com/questions/50456299/angular-6-popper-js-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!