Reputation: 161
Hi I am using lightslider with Angular4 but in that I am facing issue in initialization in lightslider()
. When I initialize light slider on any html element in index.html, it works but when I navigate to the page in which slider should be initialize it fails. For Example,
Home.html
template and Home.ts
component are the main and first page of my application and there is slider on sliderHome
element and another page is Info.html
template and Info.ts
component, which has slier on inforSlider
element. So when user lands on first page that is Home
page, slider is working but when user navigate from this page to Info
page slider is not working as it should be and it is because, it is not initialized. How can I initialize it when particular component loads.
The code is like below and it is put in index.html
page(main page),
$(document).ready(function () {
setTimeout(function () {
$('#sliderHome').lightSlider({
adaptiveHeight: true,
item: 1,
slideMargin: 0,
loop: true
});
$('#inforSlider').lightSlider({
adaptiveHeight: true,
item: 1,
slideMargin: 0,
loop: true
});
}, 500);
});
Upvotes: 2
Views: 1081
Reputation: 223
You can use the "ngAfterViewInit" lifecycle hook, through importing AfterViewInit. Angular Docs You can use it as shown below:
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);
}
Upvotes: 1
Reputation: 161
I have fixed this using following code, I have put this code in the component where slider needs to be initialized.
import { Component, OnInit, Renderer2, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/platform-browser";
@Component({
selector: 'slider-selector',
templateUrl: './slider.html',
styleUrls: ['./slider.css']
})
export class CustomeComponent implements OnInit {
constructor(
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document
) { }
ngOnInit(): void {
let script = this._renderer2.createElement('script');
script.type = `text/javascript`;
script.text = `
{
$(document).ready(function () {
setTimeout(function(){
$('#inforSlider').lightSlider({
adaptiveHeight: true,
item: 1,
slideMargin: 0,
loop: true
});
},500);
});
}
`;
this._renderer2.appendChild(this._document.body, script);
}
}
Upvotes: 2