每个组件完成加载后如何在Angular 2中运行jquery函数 [英] How to run a jquery function in Angular 2 after every component finish loading
问题描述
我尝试了所有生命周期挂钩,但无法完成所需的结果. 我需要的结果是,在加载了每个元素(组件)中的每一个之后,触发一个函数来初始化单个页面上用于不同元素的许多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.
所以可以说您具有这种结构.
So lets say that you have this structure.
首页 滑杆 小部件 产品旋转器 ..etc
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.
推荐答案
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屋!