What is the best way to increase a JSON value in a Typescript scenario? For instance, how can I add more

Is there a way to update JSON values in a TypeScript example by incrementing likes or dislikes when a button is clicked?https://i.sstatic.net/aon03.png

movies: any[] = [
   { name: "Fan", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/fan.jpg" },
   { name: "Airlift", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/airlift.jpg" },
   { name: "Wazir", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/wazir.jpg" },
   { name: "Neerja", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/neerja.jpg" },
   { name: "Bajirao mastani", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/bajirao.jpg" }
];

Answer №1

To start, make sure your HTML list is set up properly to handle click events:

HTML

<div *ngFor="let movie of movies">
    ...
    <div class="like" (click)="onLike(movie)">...</div>
    <div class="dislike" (click)="onDislike(movie)">...</div>
</div>

The template above allows you to cycle through each movie in the movies array and attach click events to the like and dislike buttons.

Typescript

export class MoviesComponent {

    movies: any[] = [
        { name: "Fan", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/fan.jpg" },
        { name: "Airlift", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/airlift.jpg" },
        { name: "Wazir", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/wazir.jpg" },
        { name: "Neerja", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/neerja.jpg" },
        { name: "Bajirao mastani", likes: 0, dislikes: 0, unseen: 0, fimage: "/images/bajirao.jpg" }
    ];

    onLike(movie) {
        // locate the movie in the array
        const index = this.movies.indexOf(movie);
        // increment the likes for the movie
        this.movies[index].likes++;
    }

    onDislike(movie) {
        // locate the movie in the array
        const index = this.movies.indexOf(movie);
        // increment the dislikes for the movie
        this.movies[index].dislikes++;
    }

}

By clicking on the buttons, you can increase the likes or dislikes for each movie. Consider assigning a unique id to each movie for safer retrieval from the array.

If you found this information helpful, please let me know!

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

Creating adaptable Object Properties using Zod

Just dipping my toes into Typescript, Zod, and Trpc. Let's say I have a schema for animals and plants. I want to keep all their shared properties in the main part of the schema, while putting more specific details into a sub-object named custom. (jus ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

Issue with compatibility between Angular v8 application and web component polyfills in IE11 causing malfunction in rendering

Recently, I've been attempting to integrate the web component polyfills into my Angular (v8) application, but unfortunately, they don't seem to be functioning properly in IE11. To showcase this issue, I have set up a new repository containing a b ...

Error TS[2339]: Property does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: ObjectId; }, never>) | null>'

After defining the user schema, I have encountered an issue with TypeScript. The error message Property 'comparePassword' does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: Object ...

Deciphering numerical information from JSON in PHP

{ "986243810235765": { "dt_server": "2022-01-15 08:45:12", "dt_tracker": "2022-01-13 11:20:30", "lat": "1.213456", "lng": "103.789012", "al ...

Zero bytes being returned by Asp.Net MVC3 when attempting to retrieve JsonResult

After exhausting all debugging options, I am still unable to identify the source of the issue. Here is the code, in all its debugging glory and silliness. [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] public ActionResult ConciergeRead([DataSourceRequest] ...

The D3 path is generating an unexpected output of 0px by 0px, causing the map not to display properly. I am currently unsure how to adjust the projection to

I am currently working on creating a world map using D3. I obtained the JSON file from the following link: https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json Below is the code snippet I'm using: // Defining SVG dimensio ...

Python tutorial: Importing geojson using JSON module and extracting specific information

import json with open("madagascar.geojson") as f: data = json.load(f) I am feeling a bit overwhelmed with this task. As a newcomer to python, the code snippet above is the extent of what I've been able to produce so far. My goal is to work with ...

Having a problem with Node.js and async.eachSeries? Want to figure out how to configure the callback function to generate a JSON file for each element in an array of

Currently, I am utilizing async.eachSeries to repeatedly call a function that generates an array called pointsForFormating. Each time this function is called, I format the pointsForFormating array and store the result in another array named pointsFormate ...

Display the HTML string as regular text in an Angular application

I'm working on a blog project with Angular. I need to display HTML content retrieved from the database as plain text for each blog post preview. The HTML formatting was done with ngx-quill. While I can render the rich text using <quill-view [conte ...

Having trouble installing @angular/cli 4 on Debian?

I'm having trouble installing @angular/cli on my Debian box. I already have the latest versions of Node.js and npm installed. Interestingly, Angular4 works perfectly fine on my Windows machine where I use it daily. However, when I try to get it runnin ...

Tips for storing a list of files within another list as a JSON file in Python

After successfully parsing data from a website using BeautifulSoup in Python, I have managed to extract the desired information. Now, my goal is to save this data in a JSON file. However, when I attempt to do so with the existing code, the data gets saved ...

Angular HttpClient request fails to initiate

Overview: A button click on a form triggers the methodForm within the component. methodForm then calls methodService in the service layer. methodService is supposed to make an HTTP POST request. Problem: The HTTP POST request is not being made. However, me ...

Error in Typescript: Property 'timeLog' is not recognized on type 'Console'

ERROR in src/app/utils/indicator-drawer.utils.ts:119:25 - error TS2339: Property 'timeLog' does not exist on type 'Console'. 119 console.timeLog("drawing") I am currently working with Typescript and Angular. I have ...

Retrieving public Twitter posts using JSON format

Looking to access the Twitter database for public tweets using JSON and jQuery? Check out this function I wrote: $(document).ready(function(){ alert("1"); $("button").click (function(){ alert("2"); $.getJSON("http://search.twitter. ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

When working with Expo and React Native in TypeScript, VS code IntelliSense recommends using 'react-native/types' instead of just 'react-native'

My React Native TypeScript setup is showing react-native/types instead of react-native in IntelliSense. How can I fix this issue? I initialized my project using npx create-expo-app MyApp --template Typescript. Here is my tsconfig.json configuration. { ...

Incorporating an expansion panel within an Angular Material table row

I'm currently working on incorporating an expansion panel, possibly a new component, similar to the mat-accordion. This will allow for a detailed view to be displayed within a mat-table row upon clicking. To better illustrate this requirement, I have ...

A guide on efficiently storing and retrieving a webpage containing two angular2 components using local storage

I've been attempting to store and retrieve a page containing two angular2 components from local storage using the following code, but the component CSS is not being applied. Here is the code I'm using to save: localStorage.setItem('pageCon ...