Currently in the process of creating a carousel displaying images, I have encountered an issue stating: "An optional property access cannot be on the left-hand side of an assignment expression."

I am currently working on an Angular Image Carousel that utilizes a model to iterate through the images. However, I am encountering an error when attempting to access the first position.

An error message stating "The left-hand side of an assignment expression may not be an optional property access.ts(2779)" is appearing.

Here is where the error occurs

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;
}
}

Answer №1

Attempting to assign a value to the result of an optional chaining expression is considered invalid:

const object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment

Link to more information on this topic

Answer №2

It seems that this error is being displayed because the find function is directly assigning a value to the object, like so:

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

If the object is not found, it will return null. In this case, how can a value be assigned to marginLeft? I believe you should first check if you have retrieved any value using the find function before setting the value of marginLeft.

This could potentially be causing an issue, especially since this code is used three times. After making these adjustments, if the problem persists, please leave a comment here and we will investigate further.

You may want to try the following approach:

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

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What allows the execution of "T[keyof T] extends Function" in TypeScript specifically for Strings?

Lately, I've been experimenting with type changes and I find myself puzzled when encountering code like the following: type DeepReadonly<T> = { readonly [k in keyof T]: T[k] extends Function?T[k]:DeepReadonly<T[k]> } // Let's defin ...

Quick tip: Adding a close 'X' button to an ng-bootstrap popover

As a newcomer to angular 5, I have been working on adding an 'x' button in the top right corner of a popover. Once this 'x' is clicked, the popover should be closed. Is there a way to achieve this using ng-bootstrap popover? Below is my ...

The reason behind my struggle with mapping API responses to an Interface in Angular

Hello everyone, I am currently working on mapping some API responses from The Muse API to an APIResponseInterface that I have created. Here's a snippet of my code: Service that sends the request: getJobs(page: number): Observable<APIResponseInterf ...

Ways to access information from a service prior to making database changes in Angular 2?

Here is my inquiry. I have a component that allows users to click a favorite button. This action updates the "favorite" column in the database. To update this value, I retrieve it from the database using the following steps: - Upon initializing the compon ...

Nuxt SSR encounters issues when modifying data variables

There is an issue with my Nuxt app where sometimes when the page loads, I encounter an error in the console that causes the page to stop loading other components. The error message reads: Cannot read properties of undefined (reading 'resolved') ...

Is there a way to prevent the leaderboard from resetting each time I restart my client?

Is it possible to prevent the leaderboard from resetting every time I restart my client? You can see an example here: https://i.stack.imgur.com/2nEPw.png Please disregard the "undefined" error, I will correct it. In the current setup, the leaderboard onl ...

Combining Several Middleware Functions in NextJs 13 for Authentication and Localization

Important Note If you are interested in exploring my code further, you can find the repository here. To access the specific code for the ott-platform, navigate to apps/ott-platform. Please make sure to create an account on Clerk and input your Clerk key i ...

What is the Angular2 equivalent of the AngularJS $routeChangeStart event?

During our time working with AngularJS, we utilized the $routeChangeStart/End event in the $rootScope to monitor changes in the route object. What is the equivalent method for monitoring route changes in Angular2? How can we achieve the same functionality ...

The error message "pipe does not exist on type" is encountered when attempting to use pipes with RxJS 6

I am in the process of upgrading my Angular 4 to Angular 6 application, which includes several RxJS operators. I attempted to pipe them together but encountered issues with the syntax. The problem arises specifically on the fifth pipe. Can someone please a ...

Tips for structuring classes in an Angular project

What is the best approach for handling API responses using classes in various programming languages like TypeScript, JavaScript, Java, or others? Consider an application that requires three resources: Account (API: /account/:id) Car (API: /account/:id/c ...

Having trouble updating properties of child components in Angular

I have a data filtering functionality where I enter values in a filter popup and successfully retrieve results. I then store this data in local storage to retain it when navigating back from another page. However, upon returning to the filter component, I ...

Tips on arranging JSON elements based on the sequence of another JSON

Currently, I am facing a challenge with sorting a list of parks (park_list) based on both distance and area. The code snippet below successfully sorts the list by distance: sortList(index){ return function(a, b){ return (a[index] === b[index] ? 0 : ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

Angular Universal experiences issues with route functionality after page reloads

Recently deployed an Angular Universal web app on Firebase. While all routes within the application are functioning properly, encountering errors when trying to access them externally. Below is the error message: functions: Starting execution of "ssr" ⚠ ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

How to link an image from a location outside the src folder in an Angular project

I am currently working on an online store project, and I have a specific issue with my image files being stored outside the src folder. The path to the images is within the flowersApp folder under img Is there a way for me to access these images from this ...

What is the process for specifying an input for a component?

When defining an input for a component like this: @Input() person: Person, some encountered the error message saying, "property 'person' has no initializer and is not definitely assigned in the constructor" even though the Person model has been i ...

concerning the integration of CSRF token in the GuestPayment feature

Greetings and thank you for taking the time to help me out. I am currently working on a project in AngularJS 2.0 where users need to be able to pay their pending bills through a GuestPayment portal. This portal does not require any login credentials and ...

Internationalization of deferred-loaded modules within the JHipster application

I created My App using JHipster, which utilizes the JhiLanguageService in the ng-jhipster library. This service relies on the JhiConfigService to configure ngx-translate without requiring manual imports and configuration of the TranslateModule in my app.mo ...

The callback function does not seem to work when using MUI v4 PropFunc

Encountering an issue with custom styling using PropFunc in Material UI (MUI) v4 (4.12.4). When providing a PropFunc in the traditional callback way to get CSS, it works as expected: const useStyles = makeStyles((theme) => { return { input: { ...