每个组件完成加载后如何在 Angular 2 中运行 jquery 函数 [英] How to run a jquery function in Angular 2 after every component finish loading

查看:21
本文介绍了每个组件完成加载后如何在 Angular 2 中运行 jquery 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了所有生命周期钩子,但无法完成所需的结果.我需要的结果是触发一个函数,在加载这些元素(组件)中的每一个之后,初始化用于单个页面上不同元素的许多 jquery 插件.

I have tried all the life cycle hooks but can't get to accomplish the needed result. The result that I need is triggering a function that initialize many jquery plugins used for different elements on a single page after every single one of these elements (components) is loaded.

假设你有这个结构.

主页滑块小部件产品旋转器..等

Home Page Slider Widgets Product rotators ..etc

这些元素中的每一个都有自己的组件,并且都是主页父组件的子组件.

Every one of these elements has it's own component and all are children of the Home page parent component.

这里我需要知道所有子组件和父组件何时加载,因此我触发了一个 jquery 函数来初始化页面上的每个插件.

And what I need here is to know when all the children components and the parent component is loaded so I trigger one jquery function to initialize every plugin on the page.

推荐答案

你会想要使用 "ngAfterViewInit" 生命周期钩子,通过导入 AfterViewInit (https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview).可以如下图使用:

You will want to use the "ngAfterViewInit" lifecycle hook, through importing AfterViewInit (https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#afterview). You can use it as shown below:

安装:

    tsd install jquery --save

    typings install dt~jquery --global --save

利用:

    import { Component, AfterViewInit } from '@angular/core';
    import * as $ from 'jquery';

    ngAfterViewInit() {
        this.doJqueryLoad();     
        this.doClassicLoad();

        $(this.el.nativeElement)
            .chosen()
            .on('change', (e, args) => {
                this.selectedValue = args.selected;
            });
    }

    doClassicLoad() {
      // A $( document ).ready() block.
      $( document ).ready(function() {
          console.log( "Unnecessary..." );
      });      
    }

    // You don't need to use document.ready... 
    doJqueryLoad() {
        console.log("Can use jquery without doing document.ready")
        var testDivCount = $('#testDiv').length;
        console.log("TestDivCount: ", testDivCount);
    }

这是一个例子:http://plnkr.co/edit/KweZYO9hk9Dz8pqDK77F?p=info

这篇关于每个组件完成加载后如何在 Angular 2 中运行 jquery 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆