Tips on maintaining the chosen product while navigating to a different component

I have a dilemma with 2 different components that are responsible for creating an invoice.

  1. The first component adds more products
  2. The second component adds invoice details

Initially, I enter the invoice details and select the client's name. The selection process involves an autocomplete feature that searches for the name. Once a client is selected, the view displays more details about that specific client. However, in the past, when adding products in a separate component and navigating to the invoice upon submission, the client's name and additional details were lost.

Here is the HTML code:

<div class="input-field col s12">
      <input formControlName="client_id" id="client_id"   matInput placeholder="Select Client*" aria-label="State" [matAutocomplete]="auto"
        autoActiveFirstOption [formControl]="client_id">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayWith" >
        <mat-option (onSelectionChange)="updateClient($event, item.client_id, 'client_id')" *ngFor="let item of filteredOptionsClient | async"
          [value]="item.clientName">
          {{ item.clientName }}
        </mat-option>
      </mat-autocomplete>
    </div>
  <div class="input-field col s12">
         Contact No:
        <span style="color:darkblue">{{selectedClient.contactno}}</span>
      </div>

And here is the TypeScript code:

  filteredOptionsClient: any;
  client_id: FormControl = new FormControl();
 ngOnInit() {
    this.cs.getAllClients().subscribe(
      client => {
        this.client = client.map((clients) => {
          this.filteredOptionsClient = this.client_id.valueChanges.pipe(
            startWith(''),
            map(val => this.filterClient(val))
          );
          return new Client(clients);
        });
        }
      }
    );
}
  updateClient(ev: any, idd: any, componentid: any) {
    if (ev.isUserInput) {
      if (componentid === 'client_id') {
        this.clientid = idd;
        console.log('idd', idd)
        this.addsale['controls']['client_id'].setValue(ev.source.value);
      } else {
        console.log('ooops');
      }
    }
     let selectedClient = new Client('')
     this.selectedClient = null;
     for (let i = 0; i < this.client.length; i++) {
       console.log('updateclient', this.client[i].client_id)
       console.log('updateclientidd', idd)
       if (this.client[i].client_id === idd) {
         this.selectedClient = this.client[i];
       }
     }
  }

Can you provide any suggestions or ideas on how to resolve this issue?

Answer №1

When it comes to accessing data across components, there are several methods available. As outlined in this article, the following approaches can be taken:

  1. Passing the reference of one component to another for communication

  2. Communication through the parent component

  3. Using a service for communication between components

If you read the above article, you'll definitely gain some insight into this topic.

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

The FlatList glides effortlessly in any direction

My FlatList allows me to drag and move it in all directions (up/down/right/left) even though it appears vertically due to styling. The scroll bar still shows horizontally, which I want to disable. How can I achieve this? This is the code snippet for using ...

The Angular APP_INITIALIZER provider is encountering an issue where one injected service is being passed as undefined, while the rest are

One of my injected services is returning as undefined in my provider, despite both services running before the provider. Any help or insight would be greatly appreciated. Below is a snippet of my code from AppModule: @NgModule({ declarations: [ // ...

Error in Angular 5: Cannot find property 'then' in type 'Observable<any>'

I encountered the following error message: "[ts] Property 'then' does not exist on type 'Observable'. How can I resolve this issue? Below is my Component code: getUsers(){ this.authService.getUsers().then((res) => { thi ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Utilize Angular 4 Router to intercept every router modification

I want to implement a Breadcrumb feature. More about Breadcrumbs on Wikipedia To achieve this, I am considering creating a Service to manage it. However, I need a way to monitor any router state changes automatically, without having to add an onActivate ...

Creating a message factory in Typescript using generics

One scenario in my application requires me to define message structures using a simple TypeScript generic along with a basic message factory. Here is the solution I devised: export type Message< T extends string, P extends Record<string, any> ...

The parameter cannot be assigned to type 'void' because it is of type 'Promise<unknown>'.ts(2345) - mockReturnValueOnce

Encountering an error while using the mockReturnValueOnce method, specifically 'Argument of type 'Promise' is not assignable to parameter of type 'void'.ts(2345)'. I attempted to solve it by writing the following code: .spyO ...

The concept of a singleton design pattern is like a hidden treasure waiting to be

My approach to implementing the singleton pattern in a typescript ( version 2.1.6 ) class is as follows: export class NotificationsViewModel { private _myService: NotificationService; private _myArray: []; private static _instance: Notificatio ...

Updating a JSON file with PHP through a form in Angular 4: A step-by-step guide

I have successfully configured the form and service to interact with the PHP file responsible for editing the JSON file. Below is a snippet of my current PHP code: if(empty($errors)) { $postdata = file_get_contents("php ...

What methods can I utilize to manage the output generated by the C# backend project?

I'm new here and I'm thrilled to be asking my first question! :) Currently, I am working on a car rental project using C# for the backend and Angular for the frontend. I have encountered an issue while trying to register a new user with existing ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Overriding default styles in an Angular component to customize the Bootstrap navbar

Is there a way to alter the color of the app's navbar when a specific page is accessed? The navbar is set in the app.component.html file, and I am attempting to customize it in a component's css file. app.component.html <nav class="navbar na ...

Utilizing custom colors in a Typescript/React/MUI Button component to enhance its design

How can I apply custom colors to the Button component without getting an error? Are there any possible solutions for this issue? I followed the module augmentation approach outlined in the documentation, but the problem persists: https://mui.com/material ...

RxJS BehaviorSubject allows you to retrieve the current value or obtain a new one depending on a specific condition

I am managing a subject that consumers subscribe to: private request$: Subject<Service> = new BehaviorSubject(null); Upon initialization, my components utilize this function: public service(id: number): Observable<Service> { return this. ...

In order to utilize Node.js/Express/Typescript, it is necessary to use the

My current project involves creating a webservice using Express, with the goal of making it executable from both localhost and an AWS Lambda function via Claudia. In order to achieve this, I am aiming to separate the app configuration from the app.listen ...

What is the best way to dynamically assign formControlNames in Angular using *ngFor?

I am currently facing a challenge with setting form controls using *ngFor over objects in an Array. The number of objects in the array can vary, sometimes resulting in only 1 object while other times multiple objects are present. My specific issue revolve ...

The standard category of class method parameter nature

I'm encountering difficulties when attempting to correctly define a method within a class. To begin with, here is the initial class structure: export class Plugin { configure(config: AppConfig) {} beforeLaunch(config: AppConfig) {} afterSe ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Resolving conflict between a user-defined class name and a built-in class name

I am creating a TypeScript Map class that utilizes the built-in Map class along with generics. The problem arises when both classes have the same name. Is there a way to import the built-in Map using explicit namespace, similar to how it's done in Jav ...