Tips for synchronizing the value of one field in a reactive form with changes in another field

I have a reactive form below where I'm using a form builder with groups.

Fig: https://i.sstatic.net/gdc7p.png

Here is the HTML code of the component

<div class="">    
    <form [formGroup]="FeedBack" (ngSubmit)="onSubmit()">
        <div
            class="grid grid-cols-6 gap-x-16 py-5 px-4 text-sm text-gray-700 border-b border-gray-200 dark:border-gray-700">
            
            <!-- Add your form fields here -->
            
        </div>

        <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
            <!-- Your table content goes here -->
        </table>

        <div
            class="grid grid-cols-5 gap-x-16 py-5 px-4 text-sm text-gray-700 border-b border-gray-200 dark:border-gray-700">
            
            <!-- Additional form controls and buttons -->
            
        </div>
        <pre>{{ FeedBack.value | json }}</pre>
    </form>
</div>

The TypeScript file associated with this component is shown below.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, FormControl } from '@angular/forms';

// Define any necessary interfaces or types here

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

  // Implement your logic here

}

I am currently facing an issue wherein I need to dynamically update the "VARIABLE NAME" column based on selections made in the property and group dropdowns. I have tried utilizing functions like "setValue", "updateValue", and "patchValue" without success. Any guidance on resolving this issue would be greatly appreciated.

Answer №1

When working with your variableName under the FormControl within a FormGroup inside a FormArray, it's important to remember that when using methods like setValue, updateValue, or patchValue, you need to specify the row index to indicate which specific FormGroup should be manipulated.

In my perspective:

  1. If you are utilizing a Reactive form, passing the event (representing the selected value) to the selectPropertyChangeHandler and selectGroupChangeHandler methods can be substituted. This way, you can access the values by referencing the FormControl along with the rowIndex.

  2. Merging the functionalities of selectPropertyChangeHandler and selectGroupChangeHandler into a single method (such as

    selectPropertyOrGroupChangeHandler
    ) is another approach.

selectPropertyOrGroupChangeHandler(rowIndex: number) {
  let formGroup = this.formArr.controls[rowIndex] as FormGroup;
  let property = formGroup.controls['property'].value;
  let group = formGroup.controls['group'].value;

  if (property && group)
    formGroup.controls['variableName'].patchValue(`${property}_${group}`);
}

Lastly, implement the method in the view:

<select
  formControlName="property"
  (change)="selectPropertyOrGroupChangeHandler(i)"
>
  ...
</select>

<select
  formControlName="group"
  (change)="selectPropertyOrGroupChangeHandler(i)"
>
  ...
</select>

Check out the demo 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

Child routes in Angular tabs are failing to display in the currently active tab

Hey there! I'm currently working on navigating my Angular application using tabs, and I've run into a bit of an issue with the child routes. Specifically, when I switch to the second child route within the second tab, the status of the tab change ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Route Not Found: URL Segment 'homePage' does not match any existing routes

Every time I click the login button, I want to be redirected to the home page. However, I keep encountering this error message : Error: Cannot match any routes. URL Segment: 'homePage' This is my route configuration: { path: 'homePage&a ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

How can a class be imported into a Firebase Cloud function in order to reduce cold start time?

When optimizing cold start time for Firebase Cloud functions, it is recommended in this Firebase Tutorial to import modules only where necessary. But can you also import a class with its own dependencies inside a function? In my scenario, I need to use Bc ...

Place the setState function within the useEffect hook

I'm currently working on a project that includes a "login" page. Once the user logs in, they should be directed to an interface displaying all their lists. To ensure this data loads immediately after login, I have implemented the useEffect hook and u ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Tips for designing a navbar specific to a profile section

I am currently working on an angular application with a navigation bar composed of anchor tags. When the user logs in, I have an ngIf directive to display my profile icon with dropdown options. However, I am facing challenges in styling it correctly. I aim ...

Syntax for nested arrow functions in TypeScript

const fetchAsyncData = (input: { value: string }): AppThunk => async (dispatch) => { try { const fetchedData = await getData({ input.value }); } catch (error) { console.log(error); } }; An error message is displayed stating "No value ...

Is it possible to perform an "input transformation" (a reverse of piping) within Angular 2?

Currently, I have an array of keywords stored as a property within my model. The goal now is to display this array as a comma-separated string in an input field and then convert it back into an array when the user makes changes. I've already implemen ...

Using GeoJson in Leaflet for map display

As I develop an Angular application with Leaflet, my goal is to showcase numerous municipalities within my country: https://i.sstatic.net/9cuSW.png In order to enhance navigation efficiency, I decided to divide my JSON file into multiple files and store ...

Exploring the process of authentication and authorization at individual route levels within Angular 4 using Keycloak

We have successfully integrated Keycloak with our application and the login and logout flow is functioning properly. However, we are facing an issue with authentication and authorization at the route level. When a user clears their browser session or the s ...

What is the best way to end a Google OAuth session using Firebase on an Ionic 2 application?

My Ionic 2 app integrates Google Authentication using Firebase. I have implemented a logout button within the app that calls the Firebase unauth() method. However, this only disconnects the Firebase reference and does not terminate the Google OAuth session ...

Encountering the message "npm ERR! missing script: start" following the update to .Net 3.0

Previously, the ASP.Net Core 2.2 code (upgraded from 2.1) did not include a start script in package.json. https://github.com/TrilonIO/aspnetcore-angular-universal/blob/master/package.json Upon upgrading to ASP.Net Core 3.0, it now requires a start script ...

Angular routing prefix allows for defining a common prefix for

I currently have a range of components that utilize the router with absolute paths for navigation in certain scenarios. Let's take for example the EntityComponent, which has an action that navigates to /otherEntity/* URLs. This setup works perfectly ...

Tips for tuning a MatTable in angular without using a filterPredicate

I'm facing a challenge with my MatTable component where I need to filter the data using previously stored values from user input. While I can verify that the values match the data, I'm unsure of how to apply filtering without relying on the filte ...

In Angular 6, triggering a reset on a reactive form will activate all necessary validators

As a beginner in angular 6, I am currently facing an issue with resetting a form after submitting data. Although everything seems to be functioning properly, when I reset the form after successfully submitting data to the database, it triggers all the req ...

Tips for importing a file with a dynamic path in Angular 6

I'm facing an issue where I need to import a file from a path specified in a variable's value. For example, it looks like this: let test = require(configurationUrl); Here, configurationUrl represents a path such as '../../assets/app.conf.j ...

When utilizing useRef and useCallback in React, the output is visible in the console log but does not appear on the page

When working with API data, it's important to remember that the extraction process is asynchronous and the state may not be available at certain times. To handle this situation, we can utilize useCallback. However, even after successfully logging the ...

NgRx: The proper method to dispatch an action with dependent data

As part of my current project with NgRx, I have implemented a facade containing a few functions: LoadMyData() { dispatch(MyActions.LoadMyDataAction({ SomeDependentData })) } In addition, I have: myDependentData$ = this.store.pipe( select(MySelec ...