Home > database >  i'm making a carousel of images and i've the error : The left-hand side of an assignment e
i'm making a carousel of images and i've the error : The left-hand side of an assignment e

Time:02-11

I am making an Image Carousel in Angular that receives a model to iterate the images, but when I try to take the first position it throws me an error.

The left-hand side of an assignment expression may not be an optional property access.ts(2779)

The error is here

export class CarouselComponent implements OnInit {
@Input() height = 500;
@Input() isFullScreen = false;
@Input() items: ICarouselItem[] = [];

public finalHeight: string | number = 0;
public currentPosition = 0;

constructor() {
 this.finalHeight = this.isFullScreen ? '100vh' : `${this.height}px`;
}

ngOnInit(): void {
this.items.map((i, index) =>{
  i.id = index;
  i.marginLeft = 0;
});
}

setCurrentPosition(position: number){
debugger
this.currentPosition = position;
this.items.find(i => i.id === 0)?.marginLeft = -100 * position;

}

setNext(){
debugger
let finalPercentage = 0;
let nextPosition = this.currentPosition   1;
if(nextPosition <= this.items.length - 1){
  finalPercentage = -100 * nextPosition;
}else{
  nextPosition = 0;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = nextPosition;
}

setBack(){
let finalPercentage = 0;
let backPosition = this.currentPosition -1;
if(backPosition >= 0){
  finalPercentage = -100 * backPosition;
}else{
  backPosition = this.items.length - 1;
  finalPercentage = -100 * backPosition;
}
this.items.find(i => i.id === 0)?.marginLeft = finalPercentage;
this.currentPosition = backPosition;
}
}

CodePudding user response:

I think this error is display because you are using find function and directly assign value to this object Like

this.items.find(i => i.id === 0)?.marginLeft = -100 * position

Suppose you didn't find the object then it will return null then How can assign value in marginLeft. I think first you have to check if You get any value using the find function and then perform set value to marginLeft.

I think this can be an issue, you are using this code 3 times. After these changes, if you can't fix let's comment here will check further.

You can try :

let item = this.items.find(i => i.id === 0);
if(item){
 item.marginLeft = -100 * position;
 // you can modify object here and do other things 

}

  • Related