【问题标题】:Angular4: jQuery and angular2-materialize not working after route navigationAngular4:路径导航后 jQuery 和 angular2-materialize 不起作用
【发布时间】:2017-07-03 04:17:56
【问题描述】:

已经使用 angular-cli 创建了一个 angular 4 项目。在 angular-cli.json 文件中导入 css 和 js。

"styles": [
    "../node_modules/materialize-css/dist/css/materialize.css",
    "styles.css"
],
"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/hammerjs/hammer.js",
    "../node_modules/materialize-css/dist/js/materialize.js",
    "../src/assets/js/init.js"
],

init.js 有以下功能

(function($) {
    $(function() {
        $('.slider').slider();
        $('.button-collapse').sideNav();
        $('.carousel').carousel();
        // $('.carousel.carousel-slider').carousel({fullWidth: true});
        $('.carousel').carousel({
            dist: 0,
            shift: 0,
            padding: 20,
        });

    }); // end of document ready
})(jQuery);

在 app.module.ts 中导入 MaterializeModule 从 'angular2-materialize' 导入 { MaterializeModule };

当我们第一次登陆页面或刷新时,滑块会按预期工作。

问题:当我们使用路由器链接导航时,页面导航正确,但没有调用 javascript 函数。

从主页路由<a routerLink="/blog/abc-1">Blog</a>

我试过了:`blog.component.ts

import { Component, OnInit } from '@angular/core';
import { MaterializeModule } from 'angular2-materialize';

import * as $ from 'jquery';

import * as Materialize from 'materialize-css';


declare let Materialize : any;

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css']
})
export class BlogComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    Materialize('.slider').slider();
  }

}

` 错误: 收到错误: ERROR TypeError: a.addEventListener 不是函数

at http://localhost:4200/vendor.bundle.js:15611:765
at Array.forEach (native)

【问题讨论】:

    标签: jquery angular materialize


    【解决方案1】:

    经过多次迭代解决。 解决方案: 如果您在 angular-cli.json 中导入 js,则无需在组件中再次导入相同的 js。导致重复,你会得到奇怪的 javascript 异常,这会误导。 只需声明它们并像下面的代码一样使用它。

    declare let $ : any;
    

    另外在 Onngint() {} 方法中再次调用 javascript 函数。这必须在将使用此函数的每个组件中调用。 下面的例子:

        ngOnInit() {
            $(function(){
                $('.button-collapse').sideNav();
            }); // end of document ready
        }
    

    记得检查文件准备好。不检查会导致脚本提前执行。

    【讨论】:

    • 你能提供更多细节吗,伙计?我尝试做Materialize('.button-dropdown'),但我收到“Materialize is not a function”错误。我试过$('.button-dropdown').dropdown(); ,但我一直看到同样的问题——下拉菜单在两页上有效(随机),但在第三页上无效。这确实帮助我解决了在ngAfterViewChecked 中使用Materialize.updateTextFields() 时遇到的错误。我在新页面加载时遇到错误;将其包装在准备好的文档中可以解决此问题。
    • 这个答案真的很有帮助。我的问题现在解决了。非常感谢............
    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 2019-02-24
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多