To emphasize the chosen item following a component's update

SCENARIO: A component named list is used to display a list of all customers. The conditions are as follows:

1) By default, the first list-item (e.g. customer 1) is selected and emitted to another component called display.

2) When any other list-item (i.e. customer) is clicked, that item is also emitted to the display component. Refer to the images below:

https://i.sstatic.net/paFx7.png https://i.sstatic.net/SIHiB.png

Contact-list component code:

HTML

<mat-selection-list>
    <mat-list-option [ngClass]="{selected : currentContact && contact.Name == currentContact.Name}" *ngFor="let contact of contacts">
           <a mat-list-item (click)="onSelect(contact)">{{ contact.Name }} </a>
    </mat-list-option>
</mat-selection-list>

TS

import { Component Input,EventEmitter,Output} from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { CustomersService } from 'src/app/services/customers.service';

@Component({
  selector: 'drt-customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.scss'],
})
export class CustomerListComponent {
 public customers:  ICustomer[] ;
   public currentContact: IContact;
 @Output()
 public select = new EventEmitter();

 constructor(public customersService: CustomersService,) {}

  public async ngOnInit(): Promise<void> {
    this.customers = await this.customersService.getCustomersList('');
    this.customerRefreshed();
  }

   public ngOnChanges(changes: SimpleChanges): void {===>To emit 1st contact by default
    if (this.contacts && this.contacts.length > 0) {
    this.currentContact = this.contacts[0];
    this.select.emit(this.currentContact);
    }
   }

  public customerRefreshed() { ====> To refresh the list after updating
    this.customersService.customerUpdated.subscribe((data: boolean) => {
        if(data) {
            this.customers = await this.customersService.getCustomersList('');
        }
    });  

  }

  public onSelect(contact: IContact): void {===> To emit contact on click
    this.select.emit(contact);
  }


}

Another component is available to perform contact updates, where a selected contact is updated using a PUT operation and then the list must be refreshed to reflect the changes. See below for the code:

update-contact component code:

public updateCustomer(): void {
    this.someCustomer = this.updateForm.value;
    this.customersService.UpdateCustomer(this.someCustomer, this.someCustomer.id).subscribe(
      () => {  // If POST is success
        this.customersService.customerUpdated.next(true);
        this.successMessage();
      },
      (error) => {  // If POST is failed
        this.failureMessage();
      }
    );
  }

services file:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ICustomer} from 'src/app/models/app.models';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})

export class CustomersService {
 private  baseUrl : string = '....Url....';
 public  customerUpdated: Subject<boolean>;


  constructor() {
    this.customerUpdated = new Subject<boolean>();
 }

  public async getCustomersList(): Promise<ICustomer[]> {
    const apiUrl: string = `${this.baseUrl}/customers`;
    return this.http.get<ICustomer[]>(apiUrl).toPromise();
 }

  public UpdateCustomer(customer: ICustomer, id: string): Observable<object> {
     const apiUrl: string = `${this.baseUrl}/customers/${id}`;
     return this.http.post(apiUrl, customer);
  }

}

The issue arises when selecting/clicking the 2nd list-item(Customer 2) for an update. After the update, the default selection reverts to the 1st list-item(Customer 1), which should not be the case. The previously clicked list-item(Customer 2) should remain in a selected state even after refreshing the list, as shown here:

https://i.sstatic.net/mAFNL.png

After the update, the previously selected list-item(Customer 2) should remain in a selected state.:

https://i.sstatic.net/jfsbt.png

Answer №1

When the page is refreshed, all information will be lost.

To prevent this, you can configure your routes as follows:

[{path:'list',component: ListComponent},
 chilren[
 {path:'list/:id',component: DetailsComponent}]

]

By using ActivatedRoute's firstchild params, you can retrieve any information related to the route.

Another option is to utilize Local Storage to store the data persistently.

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

Dealing with mistakes in an Angular service

I've been grappling with error handling in Angular. I attempted to handle errors within a service, but I'm uncertain if that's the correct approach. @Injectable({ providedIn: 'root', }) export class CaseListService { public con ...

The connection status of socket.io is always inactive

At this moment, here is what I have. There are three different attempts within the constructor comments. Currently, when the frontend launches, it continuously tries to connect with the backend in socket.io. The backend does receive the connection, but th ...

Mastering the integration of NestJS with Redis for microservices

Currently, I am diving into the world of nestjs microservices. I am curious, what commands are available for me to use? const pattern = { cmd: 'get' }; this.client.send<any>(pattern, data) Additionally, how do I go about retrieving data ...

organize the values based on their priority using reactjs

I'm facing a challenge involving two arrays of objects: array1 and array2. I need to display only three values from both arrays, with priority given to array1. The requirements are as follows: if array1 contains 3 elements, all three should be shown. ...

I find that ChangeDetectionStrategy.OnPush does not function as anticipated

Exploring the performance boost of ChangeDetectionStrategy.OnPush in Angular 2 (detailed here) has been my recent focus. However, I've encountered an interesting scenario. In my code, I have the parent component AppComponent: @Component({ selector ...

What is the best way to generate a JSON object with Angular and showcase its content through HTML?

Currently, I am dealing with a JSON object that is completely unfamiliar to me. Without knowing the keys or values of this object, I was able to successfully manipulate it and extract the necessary information. Ultimately, I have generated an array (whic ...

Firebase Angular encountering issues with AngularFirestoreModule

I have encountered a challenge with Firebase authentication in my Angular applications. Due to updated read and write rules that require auth!=null, I successfully implemented Firebase authentication in one of my apps using Angular 13. Now, I am trying to ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

After running a yarn build on a TypeScript project using a .projenrc.js file, make sure to include any packaged or additional text files in the lib folder, rather

After utilizing projen to create my typescript project, I followed these steps: mkdir my-project, git init, and npx projen new typescript. Additionally, I created two files - sample.txt and sample.js, along with the default file index.ts within the folder ...

subscribing to multiple observables, such as an observable being nested within another observable related to HTTP requests

Hello, I recently started learning Angular and I am facing a challenge with posting and getting data at the same time. I am currently using the map function and subscribing to the observable while also having an outer observable subscribed in my component. ...

Node Express and Typescript app are failing to execute new endpoints

Hello, I'm currently diving into Node express and working on a simple CRUD app for pets. So far, I've successfully created 2 endpoints that are functioning properly. However, whenever I try to add a new endpoint, Postman fails to recognize it, g ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

What is the method for retrieving interface key types in TypeScript?

My question relates to an interface. interface Some { key1: string key2: number } I am working with a function. const fn = (key: keyof Some) => { return <Some>someObject[key] } Is it possible to determine the return type based on a string ...

Attempting to deploy my Angular project on Heroku but encountering an error

While attempting to deploy my Angular project to Heroku, I followed all the necessary steps but encountered an error stating that the application failed to serve the page. As the application owner, it is advised to check the logs for more details. This can ...

typescript decorator implemented on a class that is nested within another class

Is it possible to decorate a nested property within a class? Let's explore with an example: function log(name: string = 'DecoratedProp') { return function logHandler(target: any, field: any) { // get the key ...

How can I customize a Vue component slot in Storybook 8.0.6 using Vue 3.4 and Typescript to display various subcomponents within a story?

Incorporating a variety of sub-components into my Vue 3 component based on context is proving to be a challenge. Utilizing slots seems to be the solution in Vue 3, but I'm struggling to make it work within Storybook 8, which I'm using to showcase ...

Creating formGroups dynamically within an ngFor loop inside an accordion

I am facing a challenge with an accordion feature that generates a specified number of sections x based on user input. Here is an example: After creating the sections, I need to load employee information into each section separately. However, when I load ...

Can multi-page applications be developed using Angular?

As I contemplate developing a food ordering application similar to Zomato, I have observed that Angular-like routing is used on certain pages, specifically during the ordering process after selecting a restaurant. Unlike other sections where server routing ...