Changing the Angular form based on the value selected from the drop-down menu

I am currently working on a Reactive form in Angular 7 that includes 2 dropdowns (select) which are supposed to function as cascading dropdowns. However, I am facing an issue where the cascading dropdowns are not working as intended. Whenever I select an option from the first dropdown, it displays [object Object] instead of the actual value. You can refer to this Link for more details.

Template:

<form [formGroup]="reportForm">
   <div class='col-12 col-sm-6'>
       <div class="form-group " >
          <label >Transformation Type</label>
          <select name="select" formControlName="transformationType" class="form-control"  placeholder="Select User Type" >
              <option value="0" disabled selected>Select a Criteria</option>
              <option *ngFor="let item of datasources" [value]="item">{{item.title}}</option>
          </select>
       </div>
   </div>
   <div class='col-12 col-sm-6'>
       <div class="form-group " >
           <label >User Type:</label>
           <select formControlName="whereInput" class="form-control">
               <option value="0"  selected>Select an Option</option>
               <option *ngFor="let item of units" [value]="item">{{item}}</option>
           </select>
       </div>
   </div>
</form>

Component:

this.ifscSingle.controls.transformationType.valueChanges.subscribe(data => {
   console.log(data);
}) 

Answer №1

If you want to utilize a more intricate value type for each <option> tag like object, it is recommended to use [ngValue] instead of [value]:

<form [formGroup]="reportForm">
   <div class='col-12 col-sm-6'>
      <div class="form-group " >
         <label >Transformation Type</label>
         <select name="select" formControlName="transformationType" class="form-control"  placeholder="Select User Type" >
            <option value="0" disabled selected>Select a Criteria</option>
            <option *ngFor="let item of datasources" [ngValue]="item">{{item.title}}</option>
         </select>
      </div>
   </div>
   <div class='col-12 col-sm-6'>
      <div class="form-group " >
         <label >User Type:</label>
         <select formControlName="whereInput" class="form-control">
            <option value="0"  selected>Select an Option</option>
            <option *ngFor="let item of units" [ngValue]="item">{{item}}</option>
         </select>
      </div>
   </div>
</form>

Check out this live example to see it in action.

Additionally, to ensure that the default <option> values are displayed correctly, it is advised to set them to an empty string "" in alignment with your reactive form control(s) default values. You may remove the selected attribute as Angular automatically manages this based on the current reactive form value:

<option value="">Select a Criteria</option>

<!-- your other stuff -->

<option value="">Select an Option</option>

Hope this explanation helps!

Answer №2

Make sure to update the value in the reactive form after it has been created to reflect any changes that occur.

For instance:

this.reportForm.patchValue({
  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be left out)
});

In your specific case, you should update the reportForm whenever the value for transformation type changes.

this.reportForm.get('transformationType').valueChanges.subscribe(item => {
  this.units = item.units
  this.reportForm.patchValue({
    whereInput: this.units, 
  });
}) 

When writing the HTML code, remember to use ngValue instead of value.

<select name="select" formControlName="transformationType" class="form-control"  placeholder="Select User Type" >
  <option value="0" disabled selected>Select a Criteria</option>
  <option *ngFor="let item of datasources" [ngValue]="item">{{item.title}}</option>
</select>

For a solution to your issue, refer to this working demo.

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

Following the completion of the inspection, the next step

Check out my work at this link: Unfortunately, my code is too lengthy to include here, so please refer to the link above to see the issue I am facing. The problem I am encountering is that when I click the checkbox after adding an item to the list, the r ...

Is there a way to retrieve a different value within the JavaScript code (imagepicker)?

I need help with setting up a page where users can choose an image to forward them to another page. However, I'm facing an issue when the user chooses two images at once. Can anyone provide ideas on how to handle forwarding in this scenario? You can c ...

Trouble extracting and utilizing GraphQL queries in Typescript with relay-compiler

I attempted to utilize relay with the Typescript react starter, but I am encountering several problems. It appears that babel-plugin-relay is unable to detect the graphql statements extracted by the relay-compiler. Below is my compiler script: "relay": " ...

I'm looking to design a navbar similar to the one in the provided link, and I'd like it to appear when scrolling

I'm struggling to figure out how this particular navbar was created. How can I add a navlist for Videos and make the navbar visible upon scrolling? Are there any resources, articles, or hints to help me get started with this? LINK - ...

Selecting a date in Jade's date picker

I'm currently facing an issue with getting a datepicker to function properly using Jade in a node.js and express framework. Within index.jade, I am loading the necessary javascript files like this: link(type='text/css', href='css/ui-l ...

Utilizing javascript to reverse an array and seamlessly filling in the missing elements

Consider an array containing data with increasing percentage values and some missing entries. For instance: { "months": 11, "factor": 1.31, "upperMonths": 10.5, "lowerMonths": 11.49, "limit": 20, "percentage": 8 }, { "mont ...

Load a file in JavaScript without using the cache

I'm working on a function that reads a text file from a specific location: <html> <head> <script> function readTextFile(file){ var out_text='' var rawFile = new XMLHttpRequest(); rawFile ...

The blur event in Angular Material's mat-date-range-input does not trigger if the End Date is not selected

I am currently utilizing Angular 15 along with Angular Material 14. The code for the DatePicker control is shown below. <mat-form-field class="datepicker-widget" appearance="fill"> <mat-date-range-input [formGroup]="d ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

Sorting in MongoDB v3.6 is a breeze with the powerful capabilities that the

I'm encountering an issue with arranging the most recently added item in a list of objects/items to display at the top. It's similar to a job board where I want the newest jobs to appear at the top rather than at the bottom. I attempted to use Po ...

Tips for Sending Emails from an Ionic Application without Utilizing the Email Composer Plugin

I am attempting to send an email from my Ionic app by making an Ajax call to my PHP code that is hosted on my server. Below is the code for the Ajax call: $scope.forget = function(){ $http({ method: 'POST', url: 's ...

Using PHP to create redirects within an iframe

Imagine I have embedded an iframe to showcase a different website on my own site. However, when the displayed site contains a redirect that directs to other pages within its domain, this results in the entire browser being redirected to the external site w ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

The mystery of the Accordion Effect: A Next.js/React.js issue where it slides up but refuses to

After implementing a custom accordion using next.js, I encountered an issue where the slide animation worked successfully when moving up and out upon clicking the button. However, when trying to move it back down into the content, it did not animate as exp ...

Explaining how to use the describe function in TypeScript for mapping class constructors

I am working on a function that will return a JavaScript Object with the class instances as values and the class names as keys. For example: const init = (constructorMap) => { return Object.keys(constructorMap).reduce((ret, constructorName) => ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Create a unique shader in Three.js that remains unaffected by the fog effect

I have implemented a custom shader to add glow to a sphere on my scene. However, I noticed that the fog in the scene affects the sphere but not the glow. When I zoom out, the sphere disappears but the glow remains visible. Is there a way to make the fog ...