Exploring the Solution for Connecting Angular FormArray with mat-select options and input fields

Encountering a situation where the user can open a mat-select and choose an option from the dropdown, triggering the display of a hidden form for filling. Initially, this worked fine with a static template. But now, we have transitioned to linking the mat-select and corresponding templates to options within Angular's formArray.

Currently facing two main issues:

  1. All mat-select elements in the generated forms are listening to the same event - triggering changes in one mat-select impacts others.
  2. Upon selection, all generated forms display the template linked to the first selection (index 0 in the formArray).

No syntax errors exist at present. The root of the problem seems to be related to a global variable (isPremiumAmountSelected) used to determine visibility of the forms. I prefer not to resort to splitting my component using @Input and @Output, so seeking a solution building upon the provided code.

isPremiumAmountSelected: boolean = false; 
FixedProductPrice: Boolean = undefined; 
OneFactorPricingCarValue: Boolean = undefined; 
MultiFactorPricingCarValueCarModel: Boolean = undefined;

ToggledPremiumAmountTypeDropDownOptions(data){
    this.isPremiumAmountSelected = true; 
    if(Object.is(data.value, 1)){
        this.FixedProductPrice = true; 
        this.OneFactorPricingCarValue = false; 
        this.MultiFactorPricingCarValueCarModel = false; 
    }if(Object.is(data.value, 2)){
        this.OneFactorPricingCarValue = true; 
        this.FixedProductPrice = false; 
        this.MultiFactorPricingCarValueCarModel = false;
    }if(Object.is(data.value, 3)){
        this.MultiFactorPricingCarValueCarModel = true; 
        this.FixedProductPrice = false; 
        this.OneFactorPricingCarValue = false;
    }
}
... ...

UPDATE

Managed to resolve the issue shortly after posting the query. Simplified approach similar to @Eliseo's suggestion below.

Step one: Remove TS method and global variable

Delete

ToggledPremiumAmountTypeDropDownOptions()
method and the isPremiumAmountSelected variable. Retain the other three variables.

Step two: Adjust ngIf logic in the template

To address multiple listeners reacting to the same event, access the selected option value within every *ngIf iteration instead. Eliminate the container for isPremiumAmountSelected and modify the conditional logic for each template accordingly. Also, remove any methods on the mat-select element.

... ...

Answer №1

When managing a FormArray of FormGroups within a FormGroup, you can access the formArray through a getter function.

get myFormArray()
{
     return this.myForm.get('myFormArray') as FormArray
}

<form [formGroup]="myFormGroup">
  <!--use formArrayName-->
  <div formArrayName="myFormArray">
      <!--utilizing the "getter" before iterating over "controls"-->
      <!--using [formGroupName]="i" within the loop itself-->
      <div *ngFor="let group of myFormArray.controls;let i=index"
              [formGroupName]="i">
            <!--using formControlName to input the control, for example-->
            <input formControlName="control">

            <!--to access the value of the control, you can use-->
            <div *ngIf="formArray.value[i].control==2">is two</div>
             <!-- or -->
            <div *ngIf="formArray.at(i).value.control==2">is two</div>
             <!-- or -->
            <div *ngIf="formArray.at(i).get('control').value==2">is two</div>
      </div>
  </div>
</form>

You don't need three variables to determine if it's fixedProduction, onFactor, or multipleFactor. If you choose to use three variables, you would need three arrays, but this is unnecessary as well as the (onSelectionChange) event.

NOTE: Avoid using

(ngModel)' -as ngModel does not exist- if you mean 
[ngModel]`, remember that when working with FormArrays or FormControl, you should NOT use ngModel-

NOTE2: In my answer, I demonstrated something like

form=new FormGroup({
    formArray:new FormArray([this.getGroup(),this.getGroup()])
  })
  get formArray()
  {
    return this.form.get('formArray') as FormArray
  }
  getGroup()
  {
    return new FormGroup({
      control:new FormControl(),
      fixedPrice:new FormControl(),
      oneFactor:new FormControl(),
    })
  }

I'm not sure what approach you are taking in your implementation.

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

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

Having an issue with transmitting information to the database using ajax and Laravel

I am currently working on creating a drag and drop list that can be sorted. Each time an element is dropped into a new area, the order of the list should change accordingly. I am implementing this using AJAX and Laravel, but encountering an error when drop ...

Submitting Forms in Django with AJAX for Seamless User Experience

As a newcomer to Python, I might be missing an easy fix. I'm attempting to create a registration form using Jquery with Django. I've been following this tutorial When I click the button, I see a success message in the alert, but nothing gets sa ...

Variable that can be accessed globally in Node.js

Within my node.js server-side code, specifically in a post route accessed through form submission, I have a variable named username. I want to find a way to use this same variable in a different post route. app.post("/login", function(req, res) { var ...

The reducer I have is inexplicably returning undefined even though I'm certain it was added to combineReducers

After countless hours of debugging, everything seems to be in working order but the problem still persists. The main reducer file is located at reducers/index.js // @flow import { combineReducers } from "redux"; import blocks from "./blocks"; import user ...

Unable to reach the sub-component of the JSON object that was returned

For some reason, I can't seem to access a sub object of a returned $Resource object that fetched a group of JSON objects. It's baffling me. Resource > $resolved: true > $then: function (b, g) {var j=e(),h= > data: Object > 519bc5f6 ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

Creating an HTML form that allows for multiple entries without the need for JavaScript serialization

I'm in the process of creating a straightforward form that allows users to add multiple photos before uploading. Right now, I'm manually generating an object using JavaScript. var objArr = []; for(var i = 0; i < arrayOfInputs.length; i++){ ...

My vanilla JavaScript code isn't running the smooth scroll function as expected

Struggling to incorporate smooth scroll on Safari using Vanilla js. Despite following the documentation to a tee, the implementation is still not functioning as expected. Outlined below is the vanilla.js code: (function() { scrollTo(); })(); function ...

Explore the functionalities of RxJS filter operators by applying them to a stream of arrays

Is it possible to work with a stream of arrays, such as filtering, and then emit the arrays again without concatenating the elements of the arrays or using regular array operators? For example, if I have an observable containing a single array, I can perfo ...

Aligning divs, prevent duplicate HTML within multiple divs

Currently, I am attempting to troubleshoot a jsfiddle issue. The main problem lies in my desire for the first two divs (with class="fbox") to be aligned next to each other on the same level. Furthermore, I am looking to enable dragging the image into the ...

Is it possible to modify the host header within an Angular app?

I'm experiencing a vulnerability issue and to resolve it, I need to utilize SERVER_NAME instead of the Host header. Is it possible to accomplish this using Angular? ...

Tips for personalizing the webpack compilation process for transforming .vue files into .js files?

As a beginner in the realm of webpack plugins, I've grasped the idea behind the html-webpack-plugin, which empowers users to personalize the generation process of html files by webpack. In a similar vein, I am on the quest for a plugin tailored for . ...

Unable to transfer files, encountering issues with PHP and AngularJS integration

I am currently working on uploading files using both AngularJS and PHP. For the AngularJS part, I am utilizing angular-file-upload from https://github.com/danialfarid/angular-file-upload. I suspect that the issue lies in my PHP code, as it fails to move ...

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

Enhance and Modify feature using Javascript

I'm facing two issues with my product information form. Firstly, after I submit the data, I want the input fields to be cleared automatically. Secondly, the edit function doesn't seem to work at all. I'm quite stuck on how to resolve these p ...

Refrain from revealing AngularJS code before activating it

My AngularJS code displays every time I reload the page https://i.sstatic.net/bzYrr.png Issue: The code appears even when my internet connection is slow or the page does not fully reload. I only want it to display the result. I would appreciate any sugg ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

Positioning html images to overlap each other without losing the ability to click

Currently, I am facing a challenge with positioning two images over each other. The back image should be at the bottom, while the center image needs to be on top of it. Additionally, there is a requirement for placing a random link (in this case google.com ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...