Pass information to various elements using Angular emit

On the product editing page, there's a button that triggers desi calculation. Clicking on this button opens a modal with different components. The desi calculation is done in the modal by gathering necessary information from the user. When I printed this user input to the console on the product editing page, the gravity value appeared as length which puzzled me. I tried to shorten and clean up my emit structure but couldn't find the reason behind the mix-up.

I attempted to send all the data in one emit, but encountered an error because the emit only accepted single data values.

Modal Component:


  @Output() dimensionalWeightCalculated: EventEmitter<number> = new EventEmitter();
  @Output() width: EventEmitter<number> = new EventEmitter();
  @Output() length: EventEmitter<number> = new EventEmitter();
  @Output() gravity: EventEmitter<number> = new EventEmitter();
  @Output() height: EventEmitter<number> = new EventEmitter();

...

 calculateDesi(): void {
    this.submitted = true;

    if (this.desiForm.valid) {
      const { length, width, height, gravity } = this.desiForm.value;
      const dimensionalWeight = gravity ? parseFloat(gravity) : (length * width * height) / 3000;
  
      this.dimensionalWeightCalculated.emit(dimensionalWeight); // Only emit a single value
      this.length.emit(length);
      this.length.emit(gravity);
      console.log(gravity)
      this.width.emit(width);
      this.height.emit(height);
  
      this.modalService.dismissAll();
    }
  }

Product Edit Component:

openDimensionalWeightCalculator(): void {
    const modalRef = this.modalService.open(DimensionalWeightCalculatorComponent, { centered: true, size: 'lg' });

    modalRef.componentInstance.dimensionalWeightCalculated.subscribe((dimensionalWeight: number) => {
      console.log('Calculated dimensional weight:', dimensionalWeight);
      this.productEditForm.get('ProductDetail')?.get('dimensional_weight')?.setValue(dimensionalWeight.toString());
      modalRef.close();
    });

    modalRef.componentInstance.length.subscribe((length: number) => {
      console.log('length:', length);
      this.productEditForm.get('ProductDetail')?.get('length')?.setValue(length.toString());
      modalRef.close();
    });

    modalRef.componentInstance.gravity.subscribe((gravity: number) => {
      console.log('gravity:', gravity);
      this.productEditForm.get('ProductDetail')?.get('weight')?.setValue(gravity.toString());
      modalRef.close();
    });

    modalRef.componentInstance.width.subscribe((width: number) => {
      console.log('width:', width);
      this.productEditForm.get('ProductDetail')?.get('width')?.setValue(width.toString());
      modalRef.close();
    });

    modalRef.componentInstance.height.subscribe((height: number) => {
      console.log('height:', height);
      this.productEditForm.get('ProductDetail')?.get('height')?.setValue(height.toString());
      modalRef.close();
    });
  }
}

Current Console Output:

  • Calculated dimensional weight: 4
  • length: 1
  • length: 4
  • 4
  • width: 2
  • height: 3

Answer №1

If we want to retrieve all values at the same time, we can utilize combineLatest from rxjs.

triggerDimensionalWeightCalculator(): void {
    const modalRef = this.modalService.open(DimensionalWeightCalculatorComponent, { centered: true, size: 'lg' });
    combineLatest(
       modalRef.componentInstance.dimensionalWeightCalculated,
       modalRef.componentInstance.length,
       modalRef.componentInstance.gravity,
       modalRef.componentInstance.width,
       modalRef.componentInstance.height,
    ).subscribe(([
       dimensional_weight,
       length, 
       gravity, 
       width, 
       height
      ]: Array<any>) => {
          const ProductDetailCtrl = this.productEditForm.get('ProductDetail');
          if(ProductDetailCtrl) {
               const patchValueObj = {
                   dimensional_weight,
                   length, 
                   gravity, 
                   width, 
                   height 
               };
               // filter out undefined and falsy values except zero
               const result = {};
               const patchValueObjFiltered = Object.keys(object).forEach(k => (object[k] || object[k] === 0) && (result[k] = object[k]));
               
               ProductDetailCtrl.patchValue(result);
          }
          modalRef.close();
    });
}

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

Use RxJS to ensure one observable waits for another observable to emit a non-null value

I am currently facing an issue with my setter function in TypeScript. In this setter, I assign a class member observable called systemAreasOptions$. The reason behind doing this in the setter is because it needs to wait for the observable mappedItem$ to ...

Develop unique web components and distribute them across various frameworks

Currently, I am working on two projects that utilize Angular and React. I have noticed that certain components are duplicated in both projects. To streamline this process, I am considering creating a company library where I can develop custom components on ...

A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length do ...

Tips on adjusting the Leaflet Map's zoom level to display all markers in React Leaflet

I am currently working on a project with React Leaflet map that requires changing the center and zoom based on a set of markers. The goal is to adjust the zoom level so that all the markers are visible on the map. To achieve this change in view, I am util ...

I am puzzled as to why I am receiving the error messages stating that [ngForm] is not recognized as a valid property for the form element, and that [ngClass] is not a recognized

I've been working on this code in Angular 14 for a large client project. The standard imports are listed below, along with a snippet of the .html page: import { Component, OnInit, ViewChild } from "@angular/core"; import { FormBuilder, FormC ...

Error: It is not possible to add the "providers" property as the object is not extendable within N

Ever since updating to the latest version of NGRX, I've been encountering an issue: users$= createEffect(() => this.actions$ .pipe( ofType(users.LOAD_USERS), tap((action: users.LoadUsersAction) => { action.item.name = ...

Steps for sending an image to Cloudinary using the fetch API

Struggling to figure out how to successfully upload a file to Cloudinary using fetch on my front-end. After consulting the documentation and various StackOverflow threads, I'm still facing a frustrating 400 error: export async function uploadImageToCl ...

I want to learn how to pull all the files from a Google Drive folder using the Google Drive API and then transfer them to a Spring Boot server,

I need to download all the files in a folder using the Google Drive API. Unfortunately, this API does not support downloading all files at once. The workaround is to retrieve all the files in the folder and then download each file individually. I have succ ...

Testing the React context value with React testing library- accessing the context value before the render() function is executed

In my code, there is a ModalProvider that contains an internal state managed by useState to control the visibility of the modal. I'm facing a dilemma as I prefer not to pass a value directly into the provider. While the functionality works as expecte ...

Having difficulty in getting the heading to align with the left side

Looking for some guidance on creating a dynamic page similar to this DemoPage. The goal is to have the content editable and pulling data from the backend. However, I am facing challenges in achieving the desired layout as shown in the sample page CreatedPa ...

Error in Typescript: The property 'a' is not defined in the type 'A'

Here is an example of the different types I am working with: type Place = { address: string } type Location = { latLng: string } type User = { name: string } & (Place | Location) When attempting to parse the data using this structure, I enco ...

Adjusting linear gradient when the color picker is modified

My website has a default linear gradient over an image, which is controlled by the following HTML and TypeScript code: <header [style.background-image]="cv2HeaderStyle('0, 0, 0, 0.1', '0, 0, 0, 0.8')"></header> cv ...

The ng command seems to be malfunctioning when executed from a separate directory

After selecting a different folder for my new angular project, I encountered an error every time I tried to run an ng command: 'ng' is not recognized as an internal or external command, operable program or batch file. I attempted to resolve ...

Having difficulty attaching data in Angular 2

I am attempting to populate the countries data into my px-component, which happens to be a typeahead. You can find the Codepen link here. When I directly bind the data in HTML, the typeahead successfully suggests a list of countries. However, when I atte ...

Tips for anticipating a string that begins with a particular variable

One of the challenges I'm facing involves a simple function that creates a string from a complex object. To illustrate, consider the following implementation: public generateMessage(property: string): string { return `${property} more text.`; } ...

Trouble with HTTP post response handling in Angular 8

I'm attempting to download the server response content as a CSV file, but I've encountered two errors in the process. Here is the method I am using: generateCsv(exportModel: any) { let headers={}; return this.http.post<any>(Report ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

What steps can I take to ensure that Angular component animations are triggered by changes to CSS classes, instead of relying on static

I've developed a unique block-cursor date/time input field that utilizes Angular states and animations to showcase various ongoing or transitional states. These input fields are live on this website: export const BACKGROUND_ANIMATIONS = trigger(&apos ...

Error in Angular 2/Typescript compilation: The property 'body' is not found on the type 'Response'

fetchVerificationCode(phoneNumber) { let endpoint = `${remote}/secure/verify/${phoneNumber}`; return this._http.get(endpoint) .toPromise() .then(data => { console.log(data.response); <--- PROBLE ...

On the subsequent iteration of the function, transfer a variable from the end of the function to the beginning within the same

Can a variable that is set at the end of a function be sent back to the same function in order to be used at the beginning of the next run? Function function1 { If(val1.id == 5){ Console.log(val1.id val1.name) } else{} Val1.id = 5 Val1.name = 'nam ...