简体   繁体   English

Angular2 JQuery,如何制作document.ready函数

[英]Angular2 JQuery, how to make the document.ready function

I could use some help in order to make the JQuery function run without any button click. 我可以使用一些帮助,以便在没有任何按钮点击的情况下运行JQuery函数。 Right now it only works when I have a button to click on, so the JQuery will fire. 现在它只有在我有一个按钮点击时才有效,所以JQuery会激活。

Code

declare var jQuery: any;

@Component({
selector: 'home-component',
providers: [],
moduleId: module.id,
encapsulation: ViewEncapsulation.None,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
directives: [BannerComponent],
})

export class HomeComponent implements OnInit {

    constructor(public productService: ProductService, private elref: ElementRef) {

    }

    ngOnInit(): any {
        console.log("jQuery here");
        jQuery(this.elref.nativeElement).find('button').on('click', function ()          {
            jQuery('#owl-example').owlCarousel();
        });
    }

}

This code is ofc inside a component. 此代码在组件内部。 It finds the button, and on click, it will run the jQuery function. 它找到了按钮,点击后,它将运行jQuery函数。

What I want is to make this line: 我想要的是这条线:

jQuery('#owl-example').owlCarousel();

Fire when the ngOnInit is called (without any button click). 调用ngOnInit时触发(不点击任何按钮)。 To do so I need to implement the JQuery: 为此,我需要实现JQuery:

$(document).ready(function() { }

The problem here is that it does not work :) What I have tried so far are this peace of code: 这里的问题是它不起作用:)到目前为止,我所尝试的是代码的和平:

ngOnInit(): any {
    console.log("jQuery here");
    jQuery(this.elref.nativeElement).ready(function() {
        jQuery('#owl-example').owlCarousel();
    });
}

Hope someone can help. 希望有人能提供帮助。

I would guess that on ngOnInit the element with id #owl-example does not exists yet, because it is in the same component as where the ngOnInit gets called. 我猜想,在ngOnInit与ID的元素#owl-example不存在的,但因为它是在相同的组件,其中ngOnInit被调用。 You have to use the ngAfterViewInit function: 你必须使用ngAfterViewInit函数:

ngAfterViewInit(): void {
   jQuery('#owl-example').owlCarousel();
}

You can then be sure that any element in your component exists in the document. 然后,您可以确保组件中的任何元素都存在于文档中。

You can write this code within ngAfterViewInit hook 您可以在ngAfterViewInit钩子中编写此代码

ngAfterViewInit(){    
  jQuery('#owl-example').owlCarousel();
}

I did it and it works! 我做到了,它的确有效!

import { Component, OnInit, AfterViewInit } from '@angular/core';

declare var jQuery: any;

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

  ngAfterViewInit(): void {
   jQuery('.slider').slider({full_width: true});
}


  constructor() { }

  ngOnInit() {


  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM