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

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

How can one properly conduct a health check on a Twilio connection using TypeScript?

How can I create an endpoint in TypeScript to verify if the Twilio connection is properly established? What would be the proper method to perform this check? Below is a snippet of my current code: private twilioClient: Twilio; ... async checkTwilio() { ...

What is the process for dynamically loading a component by its name in Angular 2?

I am currently incorporating dynamic loading of angular components in my application by using the following code snippet. export class WizardTabContentContainer { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() TabCont ...

Launching an Ionic 2 app with Angular 2 from a different native application

We are currently in the process of developing an application using a mobile framework called MAF. Additionally, we have another app which was built using Angular 2/Ionic 2. Our goal is to launch this Angular2/Ionic2 app from within the MAF-built app. For ...

How to Measure the Length of an Undefined Value in Jasmine Angular Unit Tests

Here's a function that I have: updateParts(enviromentContainsAllParts: PartsContainsAllParts): Observable<boolean> { const enviroment = cloneDeep(this.enviroment); enviroment.containsAllPart = enviromentContainsAllParts.containsAllPart ...

Is there a way to temporarily pause HTTP calls?

Looking for a solution to this problem I'm facing with the code below: while (this.fastaSample.length > 0) { this.datainputService .saveToMongoDB(this.fastaSample.slice(0, batch)) .subscribe(); } The issue is that I can't send all ...

A guide on retrieving data from Firestore using TypeScript

I've been diving into a chat project using Angular, and Firestore has given me a bit of trouble. Trying to get the hang of typescript while working with it. Within app.module.ts, kicking things off with: import { provideFirebaseApp, getApp, initi ...

Is it feasible to send a variable to angular.json in order to prevent repetitive code?

I'm searching for a strategy to efficiently pass data to the angular.json file, eliminating the need for redundant build configurations. To illustrate my point better, let's use an example. Currently, in my angular.json file under the configurati ...

Property input not being refreshed upon using callback function

One challenge I am facing is updating a property in a child component whenever there is a push notification from Firebase. Everything seems to be set up correctly with Firebase and the property as an input in the child component. Interestingly, when I manu ...

Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array. component.ts public checkDevi ...

"Dealing with Angular 9's mat-table and the pesky ExpressionChangedAfterItHasBeenChecked

I am facing an issue with my Angular 9 component that has multiple mat-tables. One of the tables contains rows with input fields bound to a reactive form array. While binding the table to the form array works well, I encounter an error when loading the for ...

Guide on exporting a function from a module as a class property

How to export a function as a class property from a module? Even if modifiers such as public are added, when a class property points to a function within a module, it behaves as though it is private. There are multiple ways to define a property (a, b, c ...

Tips on fixing the "TypeError: Cannot read properties of undefined (reading 'lookup')" error message that occurs when running npm install

After successfully running npm install on a freshly cloned Angular project, I encountered an error with the node_modules when trying to launch the application using ng s. Could this issue be related to the version of Node.js being used? \node_modules& ...

What is the best way to add all the items from an array to a div element?

I am currently facing an issue where only the last object in my array is being added to my div using the code below. How can I modify it to add all objects from the array to my div? ajaxHelper.processRequest((response: Array<Vehicle.Vehicle>) ...

"What could be the reason behind the injected service not being successfully passed from the parent component to the child component when navigating using route.navigate in Angular

I currently have a parent component and a child component set up in my project. (parent component) @Component({ selector: 'app-parent', providers: [SimpleService] }) (child component) @Component({ selector: 'app-child' }) Everyt ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

What causes a slow disappearance of both the form element and its child elements when the visibility attribute is set to hidden on the

Have you ever noticed that the child elements of an element form hide slowly when using visibility:hidden, but hide quickly when using display:none? This slow hiding can negatively impact user experience. I tried to find information on this issue, but eve ...

Tips for verifying that parameters possess designated characteristics in TypeScript

How can I ensure that data2 and data3 work correctly, while data1 triggers an error if the data type is not specified as shown in the code below? I need to validate that when a user enters params like {name: 'aa', age: 20}, it should throw an er ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

The directive does not function properly when used across multiple files

Struggling with @Directives and @Hostlisteners - seeking assistance The directive added to the input seems unresponsive, failing to trigger any events or console.log(). I'm puzzled and frustrated as there appears to be a missing piece of the puzzle t ...