Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this:

<div *ngFor="let person of persons">
{{person.name}} {{person.surname}}
<button class="btn {{mmm}}" (click)="selectPerson(person.id)">select</button>

Each user has their own button and when I click on a button, it should change the color of only that specific button.

In my person.component.ts

persons: IPersons[];
mmm: any = 'btn-success';

selectPerson(id: number) {
    this.persons.forEach(element => {
        if (element.id === id) {
            element.clicked = true;
            this.mmm = 'btn-danger';
        } else {
            element.clicked = false;
            this.mmm = 'btn-success';
        }
    });
}

In my person.model.ts

export interface IPerson{
id?: number;
name?: string;
surname?: string;
age?: number;
self_number?: string;
parent_number?: string;
home_number?: string;
photoContentType?: string;
photo?: any;
clicked?: boolean;}

export class Person implements IPerson{
constructor(
    public id?: number,
    public name?: string,
    public surname?: string,
    public age?: number,
    public self_number?: string,
    public parent_number?: string,
    public home_number?: string,
    public photoContentType?: string,
    public photo?: any
) {}}

Answer №1

Include an additional field in each individual's profile data. Give it a name like clicked.

Utilize the ngClass directive within your HTML code. This will apply the specified class only if the clicked status of that specific person is true.

<div *ngFor="let person of persons">
    {{person.name}} {{person.surname}}
<button class="btn" [ngClass]="{'mmm': person.clicked==true}" 
    (click)="chosePerson(person.id)">choose</button>

In your TypeScript file, iterate through the list and set the clicked-field to true for the selected person while resetting all others to false;

chosePerson(id: number) {
    this.persons.forEach(element => {
        if (element.id === id) {
            element.clicked = true;
        } else {
            element.clicked = false;
        }
    });
}

This method should effectively handle the task at hand.

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

Retrieve the stored information from a variable

Can anyone help me with a coding issue I'm facing? I have a constant called data, which contains two values - prediction and probability. What is the best way to access and retrieve both values? type ML = { prediction: string; probability: num ...

Tips for displaying dynamic images using the combination of the base URL and file name in an *ngFor loop

I have a base URL which is http://www.example.com, and the file names are coming from an API stored in the dataSource array as shown below: [ { "bid": "2", "bnam": "ChickenChilli", "adds": "nsnnsnw, nnsnsnsn", "pdap": " ...

TypeScript - The key is missing from the type definition, yet it is present in reality

I'm currently working on developing my own XML builder using TypeScript, but I've run into a significant issue: Property 'children' does not exist in type 'XMLNode'. Property 'children' does not exist in type &apos ...

What are the tips for using ts-node in the presence of errors?

While developing, I have encountered some issues with ts-node. When I need to test something, commenting out code is my usual approach. However, when using ts-node, I keep getting this error message: 'foo' is declared but its value is never rea ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

Prisma atomic operations encounter errors when attempting to update undefined values

According to the Prisma Typescript definition for atomic operations, we have: export type IntFieldUpdateOperationsInput = { set?: number increment?: number decrement?: number multiply?: number divide?: number } Let's take a look at the Pris ...

The state data is not being properly updated and is getting duplicated

While developing a loop to parse my API data, I encountered an issue where the values obtained were not being captured properly for dynamically loading corresponding components based on their characteristics. The problem arose after implementing useState() ...

Steps for updating a server component after redirectionWould you like to know how

One of my server components fetches and displays data only when the user is authorized: function CheckAuthorization() { const isAuthenticated = // check if user is authorized return ( <div> {isAuthenticated ? ( <DisplayAutho ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...

The intersection type of an array gets lost when used in the map() function

Running into an issue with my TypeScript code snippet where the mapped type is losing intersection type information inside the map(). type Foo = { foo: number }; type Bar = { bar: string }; const arr: Foo[] & Bar[] = [{ foo: 1, bar: 'bar' }] ...

Using a dictionary of objects as the type for useState() in TypeScript and React functional components

I am in the process of transitioning from using classes to function components. If I already have an interface called datasets defined and want to create a state variable for it datasets: {[fieldName: string]: Dataset}; Example: {"a": dataset ...

The datatable only accepts arrays and Iterable data types

While attempting to perform a CRUD operation with the datatable, I encountered an error message "Only arrays and iterables are allowed in datatable" upon clicking the submit button for creation. The console pointed out the error in the component.html file ...

Combine two arrays into one

When attempting to combine two arrays, the result looks like the image linked below: I want the merged array to resemble the following example: {0: {…}, storedArr: Array(2)} 0: address: "ifanio de los Santos Ave, Mandaluyong, 1550 Metro Manila, Phi ...

Strange activities observed during the management of state in react hooks, where the splice() function ends up eliminating the

My current setup involves maintaining a state to handle the addition of new JSX elements: const [display, setDisplay] = useState<IDisplay>({ BookingFormDropDown: [], } ); I have a function in onClick() which adds an elem ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Configuration options for Path Aliases in TypeScript

In my Next.js project, I am utilizing TypeScript and have organized my files as follows: |-- tsconfig.json |-- components/ |---- Footer/ |------ Footer.tsx |------ Footer.module.sass My path aliases are defined as:     "paths": {       ...

Utilizing Typescript to Transfer Data from Child to Parent in React

Attempting to pass data from a Child Component to a Parent component using Typescript can be challenging. While there are numerous resources available, not all of them delve into the TypeScript aspect. One question that arises is how the ProductType event ...