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

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

我在 angular 中找不到任何地方的华丽弹出窗口 问题是 jquery

无法识别 magnificPopup

为了比较,我使用了 jquery-confirm 并且有效。该过程与 magnific popup 相同,唯一不同的是调用方法 $.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)

你可以试试这个:

import $ from "jquery";
import 'magnificPopup'; // <=== if it exist into your node_module folder

否则,将其导入您的 index.html。

为了让它发挥作用,我采用了以下步骤:

我用 cli 创建了一个新项目 ng new ng-magnific-popup 我运行npm install --save jquery magnific-popup 我将 app.component.html 更新为

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

我将app.component.ts更新为

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

我还通过将 "../node_modules/magnific-popup/dist/magnific-popup.css" 添加到样式数组来更新 .angular-cli.json 文件以包含他们的 css 文件。

GitHub repo 完整代码。

谢谢peinearydevelopment!。但是对我来说 AfterViewChecked 有效,出于某种原因 AfterViewInit 没有。

import { Component, OnInit, AfterViewChecked  } from '@angular/core';
import * as $ from 'jquery';
import 'magnific-popup';


@Component({templateUrl: 'home.component.html'})
export class HomeComponent implements AfterViewChecked   {
    @ViewChild('img')   imgElement:ElementRef; 
    @ViewChild('video') videoElement:ElementRef; 

    ngAfterViewChecked (): void {
   
        if (this.imgElement) {
           $(this.imgElement.nativeElement).magnificPopup({ type: 'image' });
        }

        if (this.videoElement) {
            $(this.videoElement.nativeElement).magnificPopup({ type: 'iframe' });
         }
 
    }  
}