简体   繁体   中英

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. Right now it only works when I have a button to click on, so the JQuery will fire.

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.

What I want is to make this line:

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

Fire when the ngOnInit is called (without any button click). To do so I need to implement the 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. You have to use the ngAfterViewInit function:

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(){    
  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() {


  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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