Search code examples
jqueryangularmagnific-popup

Angular 2+ TypeError: $(...).magnificPopup is not a function


I cannot find anywhere for magnific popup in angular the problem is magnificPopup is not recognized by jquery

for comparison, i used jquery-confirm and it works. the process is the same like magnific popup the only different is the calling method which is $.confirm({jquery-confirm stuff})

angular-cli.json

...    
"scripts": [
            "../node_modules/jquery/dist/jquery.js",
            "../node_modules/magnific-popup/dist/jquery.magnific-popup.min.js",
            "../node_modules/bootstrap/dist/js/bootstrap.js",
...

package.json

...
  "googleapis": "19.0.0",
    "jquery": "3.2.1",
    "jquery-confirm": "^3.3.2",
    "magnific-popup": "^1.1.0",
    "moment": "2.18.1",
...

Ts

import * as $ from "jquery";
...
setTimeout(()=>{
            $(document).ready(function($){
                alert();
                $('.popupImage').magnificPopup({
                    type: 'image'
                    // other options
                    ,
                });
            });

        },2000)

Solution

  • To get this to work, I utilized the following steps:

    I created a new project with the cli ng new ng-magnific-popup I ran npm install --save jquery magnific-popup I updated app.component.html to

    `<a #img href="assets/BingWallpaper-2018-03-23.jpg">img</a>`
    

    I updated app.component.ts to

    import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
    
    import * as $ from 'jquery';
    import 'magnific-popup';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements AfterViewInit {
      @ViewChild('img') imgElement: ElementRef;
    
      ngAfterViewInit(): void {
        $(this.imgElement.nativeElement).magnificPopup({ type: 'image' });
      }
    }
    

    I also updated the .angular-cli.json file to include their css file by adding "../node_modules/magnific-popup/dist/magnific-popup.css" to the styles array.

    GitHub repo with full code.