What is the best way to associate a select dropdown with a form in Angular 2 using formBuilder

After conducting some research, I was surprised to find that the process is not as straightforward as I had expected.

I have come across various methods using ngModel, such as Bind and fetch dropdown list value in typescript and Angular2, among others. However, I am looking for a way to easily bind my selected option to my formControlName variable.

This is what I have attempted:

.HTML

 <form id="myForm" name="father" [formGroup]="fatherForm" (ngSubmit)="createFather()">
     <div class="row">
         <select formControlName="pref" id="f">
              <option value=null disabled selected>Prefijo</option>
              <option *ngFor="let item of prefs" [ngValue]="hello">{{item.name}}</option>
          </select>

      </div>
 </form>

.TS

fatherForm: FormGroup;  

this.fatherForm = this.formBuilder.group({
          pref: ['AA']
});

 this.prefs=[
     {name: "AA"},
     {name: "BB"}
  ];

The default value works. However, when I choose 'BB', the default value remains selected. The same issue occurs when the default value is set as an empty string.

This method is recommended by Harry-ninh in Bind Select List with FormBuilder Angular 2

What could be the mistake in my implementation?

Note: there are other form inputs present, but they have been omitted for simplicity's sake.

EDIT

I also attempted to replicate the exact same example in this Plunkr, but it did not work either. http://plnkr.co/edit/Rf9QSSEuCepsqpFc3isB?p=preview Upon submitting the form, it shows that the value has not been altered.

Answer №1

Greetings! Please follow these instructions:

<form id="myForm" name="father" [formGroup]="fatherForm">
   <div class="row">
     <select formControlName="pref" id="f">
          <option value=null disabled selected>Prefijo</option>
          <option *ngFor="let item of prefs" [value]="item.name">{{item.name}}</option>
      </select>

  </div>
   <button type="submit">Submit</button>
</form>
<p>Value: {{ fatherForm.value | json }}</p>

Additionally, use the following code snippet:

name:string;
fatherForm : FormGroup;
prefs=[
 {name: "AA"},
 {name: "BB"}
];
constructor(fb:FormBuilder) {
  this.fatherForm = fb.group({
    pref : [this.prefs.name]  
 });
}

You can also view a working example on Plunkr.

I hope this information proves useful to you.

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

Implementing Firebase with Angular 4 Material for Autocomplete Feature

I am facing an issue with outputting and filtering the $key object of Firebase. When trying to load, I encounter this error message: Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports b ...

Pattern matching to eliminate line breaks and tabs

Hey there, I'm working with a string: "BALCONI \n\n\t\t\t\t10-pack MixMax chocolade cakejes" and trying to tidy it up by removing unnecessary tabs and new lines. I attempted using .replace(/(\n\t)/g, '&apo ...

When attempting to add a variable using the next() function, I encountered an error with the BehaviorSubject. The error message displayed was "this.count.next is not a function"

In my Angular service, there is a variable called count that I need to monitor for updates. Whenever this count variable is updated, I want to assign its new value to another variable in a separate component. import {BehaviorSubject} from "rxjs/BehaviorSu ...

Ensuring Angular applications can effectively run on Internet Explorer

In my Angular application, I have implemented the functionality where users can choose a map to select the delivery point for goods. However, there seems to be an issue with this feature in Internet Explorer (IE) - the map opens but the delivery points ar ...

Angular 2: Retrieve current currency rates based on your location

When I apply the {{listing.sellPrice | currency : undefined : 0}} code, it only displays the symbol $. However, I would like for the currency to change based on the user's location. For instance, if someone is in Europe, their currency would be shown ...

Only include unique objects in the array based on a common property

I am currently working with the following array: [ {name: "Mike", code: "ABC123"}, {name: "Sarah", code: "DEF456"}, {name: "John", code: "GHI789"}, {name: "Jane", code: "JKL01 ...

"What is the best way to calculate the total value of an array in TypeScript, taking into account the property

I'm currently working on a small Angular project that involves managing an array of receipt items such as Coke, Fanta, Pepsi, Juice, etc. Each receipt item has its own price and quantity listed. receiptItems: Array<ReceiptItem>; Here is the st ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

I need help figuring out how to incorporate dynamic checkboxes in Angular

Currently, I am working on integrating dynamic forms into my Angular application and I am referring to the https://angular.io/guide/dynamic-form guide for guidance. Specifically, I have a checkbox question that consists of more than four options to choose ...

When transmitting an ajax POST FormData object, the key and value may not be transmitted as originally configured

In my code, I am setting up a FormData object like this: const formData = new FormData(); formData.append('id', '12345678'); Next, I make a POST request using angular HttpClient. However, when I use Postman to debug the reques ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Is there a way to execute the run function of a different Component in Angular 7 without causing the current

Is there a way to execute the ngOnInit() function from one component inside another component without needing to refresh the existing page? ...

Converting JSON to TypeScript with Angular Casting

I'm facing an issue detailed below. API: "Data": [ { "Id": 90110, "Name": "John", "Surname": "Doe", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d282f2923282207202a262e2b ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

What is preventing me from setting the User object to null in my Angular application?

Currently, I am working on a project in Angular and encountering a specific issue. In my service class, the structure looks like this: export class AuthService { authchange: new Subject<boolean>(); private user: User; registerUser(authD ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Guide to vertically aligning text in an overlay using CSS within Angular 2

I currently have an overlay on my page that displays a spinner (an Angular material component) and accompanying text. This overlay covers the entire page and prevents clicking on elements below it. The spinner is positioned in the center of the page, and ...