Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'.

The specific error message states: "Error: There is no FormControl instance attached to form control element with name: 'countryName'".

Here is my code:

ngOnInit(): void {
    this.getFormControlsFields(Object.keys(this.countryKey)[0]);
  }

  getFormControlsFields(field: string) {
    const formGroupFields: any = {};
    formGroupFields[field] = new FormControl('');
    this.formFields.indexOf(field) === -1 && this.formFields.push(field);
    this.contactForm = new FormGroup(formGroupFields);
  }
  
  handleChange(value: any, type: string) {
    if (type === 'countryName') {
      this.getFormControlsFields(Object.keys(this.countryKey.states.s1)[0]);
      this.removeFormControls(['districtName', 'placeName']);
      this.fieldValues = {
        ...this.fieldValues,
        stateName: this.getFilteredList(secondLevelArr, value)
      };
    }
  }

Below is the relevant HTML code:

<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
            <div *ngFor="let field of formFields">
                <mat-form-field *ngIf="field" appearance="fill" class="w-100-per">
                    <mat-label>{{field | titlecase}}</mat-label>
                    <mat-select [formControlName]="field" (selectionChange)="handleChange($event.value, field)">
                        <mat-option *ngFor="let value of fieldValues[field]" [value]="value.id">{{value.name}}</mat-option>
                    </mat-select>
                </mat-form-field>
            </div>
            <button type="submit" mat-raised-button color="primary">Submit</button>
        </form>

Answer №1

One way to enhance control is by using the "addControl" method:

this.contactForm.addControl(
  'countryName',
  new FormControl(
    '', // yourFirstState
    Validators.required))

Alternatively, you can access the control through:

const nameControl = this.contactForm.get('countryName');

or:

this.contactForm.controls['countryName'].value

Before implementing an if() statement, check the form's value with:

this.form.controls

This snippet of code provides valuable insight into the form's current status.

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

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

Strange Node.js Issue

I don't have much experience with node.js, but I had to use it for launching on Heroku. Everything was going smoothly until a few days ago when suddenly these errors started appearing. Error: /app/index.jade:9 7| meta(name='viewport', co ...

Proceed with another ajax request only when the previous one has been successfully completed and loaded

While scrolling down and loading content into my page, I am facing an issue. The ajax executions load too quickly, causing the subsequent calls to not receive correct information from the first ajax call that is loaded into the DOM. How can I ensure that ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

What is the most effective way to move specific data from one page to another in Angular/Typescript?

Welcome to my Main Page! https://i.stack.imgur.com/m9ASF.png This is where I want to start my journey. https://i.stack.imgur.com/E8pAW.png My goal is to click the Last 1 Day button to redirect to another page with the date filter and ItemId values already ...

Losing a specific characteristic of data occurs when assigning a JavaScript object

After dedicating a full day to investigating this case, I found myself losing hope. const Tests = (state = INIT_STATE, action) => { switch (action.type) { case GET_TEST_DETAIL: return { ...state, test: {}, error ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

ajax memory leakage

Encountering a gradual memory leak issue in Internet Explorer and Firefox while utilizing a mix of ASP.NET AJAX and jQuery. The situation mirrors the one portrayed on this post: Preventing AJAX memory leaks, but with jQuery and ASP.NET AJAX instead of prot ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

Retrieving images in Angular 2 from a file upload process

Hello in my Angular 2 application I am integrating ng2-file-upload library for file uploading: <input type="file" ng2FileSelect [uploader]="uploader" multiple (change)="onChange($event)"> I am interested in creating an instance of an image object ...

Snapping a photo from the webcam for your profile picture

Is there a way to capture images using a webcam and upload them to a server in a PHP & Mysql application? I've been searching on Google but only find outdated code that is not supported in all browsers. Here are some links you can check out for more ...

Unable to retrieve the URL using the getDownloadURL function from Firebase

I have been using Firebase storage to successfully store images, however I am encountering an issue when trying to retrieve the image URL from a promise. const imageSaveHandler = (e) => { e.preventDefault(); const uploadTask = storage.ref(`i ...

Implementing a method for JQuery event handlers to access variables within a module pattern

var MODULE = (function() { var app = { hi: "hi dad", // How can I retrieve this value? onSubmitClick: function() { $('button').click(function() { console.log(hi); // Is there a way to access ...

Using jQuery to smoothly scroll horizontally to a specific div element

In my project, I aspire to create a layout similar to the BBC website: with a side scroll from section to section. Here is my code and the issue I am encountering: jsFiddle: http://jsfiddle.net/neal_fletcher/kzQFQ/2/ HTML: <div class="wrapper"> ...

Using jQuery UI to trigger Highlight/Error animations

Apologies if this question seems obvious, but I can't seem to find a clear answer anywhere... Is there a way to add a highlight/error message similar to the ones on the bottom right of this page: http://jqueryui.com/themeroller/ by simply using a jQu ...

Error message signaling that the dollar sign symbol is not defined in the Laravel framework

Hello there, I'm currently learning Laravel and following a tutorial on building a student CMS. I have integrated a datepicker and a bootstrap modal that are supposed to pop up when clicking form buttons. However, despite everything appearing correct, ...

Angular setup prompting for anonymous usage statistics collection by the Angular development team

This is my first time installing Angular and I ran into confusion at this step. The terminal message prompted me with the option to share anonymous usage data with the Angular Team at Google under their Privacy Policy. Here's what it said: ? Would y ...

Crafting a Visual Storybook with Express.js

I am currently working on developing a photo album app using MEVN. In this project, the value of req.body.ALBUM is used as the folder name and req.body.DESCRIPTION is designated for describing the content. The issue I have encountered so far is that whil ...

JSON conversion error: Unable to convert circular structure to JSON - locate problem within JSON structure

Currently, I am utilizing Contentful in conjunction with a MEAN stack. Upon querying the Contentful API, I receive a json object. contentClient.entries(query, function(err, entries){ if (err) throw err; console.log(entries); }); Lately, I have been e ...