Reputation: 498
I try to create effect with my slider (I use Swiper).
I can retrieve the exact position of the slider on move event, I can see that position updated in real time in console.log, but the changements are not reflected in DOM and I don't understand why ...
This is my component :
ngOnInit(){
this.swiper = new Swiper(containerSelector, {
width:375,
slidesPerView: 1,
initialSlide: 1
});
}
ngAfterViewInit(){
this.swiper.on('setTranslate', function(translate){
this.currentTranslate = Math.abs(translate);
this.windowWidth = window.screen.width;
if(this.currentTranslate == this.windowWidth){
// Home view
console.log("middle !");
this.scaleYahLogo = 1;
this.scaleYahIcn = 0;
this.opacityChatsGrey = 1;
this.opacityChatsColor = 0;
this.opacityProfileGrey = 1;
this.opacityProfileColor = 0;
this.headerPosi = 0;
}
else if(this.currentTranslate < this.windowWidth){
// Profile view
console.log("left !");
this.scaleYahLogo = 0;
this.scaleYahIcn = 1;
this.opacityChatsGrey = 0;
this.opacityChatsColor = 1;
this.opacityProfileGrey = 0;
this.opacityProfileColor = 1;
this.headerPosi = 0;
}
else if(this.currentTranslate > this.windowWidth){
// Chats view
console.log("right !");
this.scaleYahLogo = 0;
this.scaleYahIcn = 1;
this.opacityChatsGrey = 0;
this.opacityChatsColor = 1;
this.opacityProfileGrey = 0;
this.opacityProfileColor = 1;
this.headerPosi = 0;
}
})
}
What did I do wrong ? I struggle since yesterday ...
Thanks all folks !
Upvotes: 1
Views: 369
Reputation: 34425
This is because your modifications are made outside of angular's change detection cycle (with the on
handler)
Use ChangeDetectorRef to notify angular of your changes
import { ChangeDetectorRef } from '@angular/core';
constructor(private cdr: ChangeDetectorRef){}
this.swiper.on('setTranslate', (translate) =>{
//Your code here
this.currentTranslate = Math.abs(translate);
this.windowWidth = window.screen.width;
//...
this.cdr.detectChanges();// Call this method
});//end translate
Upvotes: 2
Reputation: 31105
this
keyword in a Javascript function()
refers to the scope of the function. To use member variables, use arrow functions. You could try the following
ngAfterViewInit() {
this.swiper.on('setTranslate', (translate) => { // <-- arrow function instead of `function()` construct
this.currentTranslate = Math.abs(translate);
this.windowWidth = window.screen.width;
if (this.currentTranslate == this.windowWidth) {
.
.
.
})
}
Upvotes: 1