What is the best way to update the value of a variable within a specific child component that is displayed using ngFor?

Hello there, I'm in need of some assistance with a coding issue. I have a parent component named "users-list" that displays a list of child components called "user" using *ngFor. Each component's class is dynamic and depends on various internal variables. When a user clicks on a component to select it, the class changes accordingly. Currently, users can select multiple components, but I want to ensure that only one is selected at any given time. How can I achieve this desired functionality?

Below is the code snippet:

Parent Component:

import { Component, Input, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { User } from '../user';
import { UtilsService } from '../utils.service';

@Component({
  selector: 'app-users-list',
  templateUrl: './users-list.component.html',
  styleUrls: ['./users-list.component.css']
})
export class UsersListComponent implements OnInit {

  usersList : User[] = []
  filteredUsersList : User[] = []
  usersSub : Subscription = new Subscription

  selectedClassNmae : String = "card-selected"

  searchValue = ""
  search(searchValue : string)
  {
    this.filteredUsersList = this.usersList.filter(x => x.name.includes(searchValue) || x.email.includes(searchValue))
  }

  constructor(private utils : UtilsService) { }

  ngOnInit(): void {
  
    this.usersSub = this.utils.getUsers().subscribe((data : any) =>
    {
      this.usersList = data
      this.filteredUsersList = data
    })

  }

  ngOnDestroy()
  {
    this.usersSub.unsubscribe();
  }

}
...

Child Component:

import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
import { Subscription } from 'rxjs';
import { User } from '../user';
import { UtilsService } from '../utils.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  @Input()
  user : User | undefined

  otherData : boolean = false
  editData : boolean = false
  ...

}
.card-completed {
    max-width: 400px;
    background-color: rgb(239, 248, 239);
    border-style: solid;
    border-color: #25a18e;
  }
...

<br/>

Answer №1

To easily manage the selected element and conditionally apply a CSS class, using a variable along with [ngClass] would be helpful:

Typescript :

export class AppComponent {
  selectedElement: any;

  items = [
    { id: 1, name: 'apple' },
    { id: 2, name: 'banana' },
    { id: 3, name: 'cherry' },
  ];
}

HTML :

<ul>
  <li
    *ngFor="let item of items"
    (click)="selectedElement = item"
    [ngClass]="{ chosen: selectedElement === item }"
  >
    {{ item.name }}
  </li>
</ul>

CSS :

.chosen {
  color: blue;
}

View the example on StackBlitz

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

We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid. In another part of my code, I have a function that successfully fetche ...

Ways to create a versatile function for generating TypedArrays instances

I'm working on a function that looks like this: export function createTypedArray<T extends TypedArray>( arg : { source : T, arraySize : number } ) : T { if( arg.source instanceof Int32Array ) { return new Int32Array( arg.arraySize ); } ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

Navigate to the identical component using Angular

There is a situation where a user visits /details;id=1. In the DetailsComponent, there is a table displaying similar objects with a button that redirects to /details;id=x, where x represents the id of the object. After clicking on the button, the URL para ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

Exploring Parquet Files with Node.js

Looking for a solution to read parquet files using NodeJS. Anyone have any suggestions? I attempted to use node-parquet but found it difficult to install and it struggled with reading numerical data types. I also explored parquetjs, however, it can only ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...

Dynamic Setting of Content-Type Header (Multipart/Data) Through Http Interceptor

I have been trying to upload a CSV file using an HttpInterceptor as a middleware. Everything works fine for normal requests, but I need to modify the request header to 'multipart/data' specifically for CSV uploads. Below is the code snippet: ex ...

What are the steps to utilize a personalized validation access form within a component?

I created a unique validator to verify if an email already exists in the database before saving a new user, however, it appears that the validator is not functioning properly. Here is my template: <form class="forms-sample" #f="ngForm" (ngSubmit)="onS ...

How do I insert a new column into the result set of a query in Prisma?

Imagine a scenario where there are two tables: User, which has fields for name and Id, and Post, which has fields for name and content. These tables are connected through a many-to-many relationship (meaning one post can have multiple users/authors and eac ...

Manipulating strings in Angular using property binding

Is there a way to concatenate the following two statements that work individually? <app-output [warnMessage]="myvalue | number:'1.0-1'"></app-output> <app-output [warnMessage]="'TEXT01' | translate"></app-output&g ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

Firebase allows for the updating of an object within a nested array

Within Firestore, I have a Document that includes a property named "items" which is of type array. This array consists of ShoppingItem objects with the specified structure: export class ShoppingItem { id?: string; name: string; checked = false; } To ...

Typescript Event Handling in React Select

I am facing an issue with my handleSelect function: const handlerSelectBank = (event: React.ChangeEvent<{ value: unknown }>) => { setState({ ...state, buttonDisabled: false, selectedBank: event }); }; Upon execution, I encountered ...

Talebook: Unable to modify UI theming color

As I embark on creating my own theme in Storybook, I am closely following the guidelines outlined here: Currently, I have copied the necessary files from the website and everything seems to be working fine. However, I am facing an issue when trying to cus ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

Electron triggers MouseLeave event on child elements

Dealing with mouse hover events can be a bit tricky, especially when working with AngularJS in an Electron-hosted app. Here's the HTML template and script I'm using: HTML: <div id="controlArea" (mouseenter) = "onControlAreaEnter()" ...

Navigating through JSON object array using *ngFor directive in Angular 4

I am trying to iterate through an array of objects stored in my JSON file. JSON [ { "name": "Mike", "colors": [ {"name": "blue"}, {"name": "white"} ] }, { "name": "Phoebe", "colors": [ {"name": "red"}, { ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...