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

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

Guide to updating 2 iframes simultaneously with a single link/button using HTML and JavaScript

Just joined the community and looking for help on how to refresh two different iframes within a single page. I came across a solution on Google that involves using getElementById. However, I've heard Firefox can be tricky with IDs. Appreciate any as ...

Error 4 encountered when attempting to upload files using Ajax to a PHP server

On my website, there is a form that looks like this: <form style="width:100%; clear:both; margin-top:50px; background:#fff; border:1px solid green" id="upload_form" enctype="multipart/form-data" class="form" action="" method="post"> <fieldse ...

What steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: 'use strict'; var Comment = require('../../../models/comment'); module.exports = { description: 'Create a Comment', notes: 'Create a comment&apos ...

Tips for modifying the language of an Angular Application's OneTrust Cookie Banner

I'm currently developing an Angular application and utilizing OneTrust for managing cookie consent. The issue I'm encountering is that while the rest of the components on the login page are properly translated into the target language, the OneTru ...

Invoking Angular component method using vanilla JavaScript

For my web application, I am utilizing Angular and require Bluetooth functionality on a specific page. I am implementing loginov-rocks/bluetooth-terminal (https://github.com/loginov-rocks/bluetooth-terminal) for establishing the Bluetooth connection, which ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Finding specific data in sessionStorage using an ID or key

I have stored data in sessionStorage and this is an example of how I save the data: $.ajax({ type: 'POST', url: 'Components/Functions.cfc?method='+cfMethod, data: formData, dataType: 'json' }).done(function(ob ...

Angular routes cause a glitch in the Bootstrap navbar, causing it to shift to the left on certain active

Apologies for the simple question, I am new to web design and couldn't find a solution even after extensive googling and searching. The issue I am facing is that when clicking on "EX5" or "EX6" in my navbar, it shifts to the left side of the screen i ...

Utilizing asynchronous false in Wordpress Ajax functionality

Is there a way to use the AJAX return value outside the function in WordPress? For example: function get_login_member($) { $.post(ajax_object.ajax_url, {action: 'getloginmember'}, function (data) { data = JSON.parse(data); ...

Determine whether the radio button has been selected

Within my HTML code, there's a radio button enclosed in a form: <mat-radio-button [(ngModel)]="boxChecked" name="boxChecked" value="boxChecked">Check me</mat-radio-button> In the TypeScript section, I've declared my boolean variable ...

The 'firestore' property is not found within the 'Firebase' type

I'm currently working on retrieving the precise time a document is generated. To achieve this task, I have included the following imports: import { Firebase } from '@ionic-native/firebase/ngx'; import { AngularFirestore } from '@angul ...

Use an EditText to capture user input, then pass the variables to a Webview by executing a javascript command

I'm currently working on a basic web application that aims to streamline the user experience by eliminating the need for repeated credential input upon website access (without saving passwords). After some exploration, I was able to identify and manip ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

Access to the server has been restricted due to CORS policy blocking: No 'Access-Control-Allow-Origin'

I’m currently encountering an issue with displaying API content in Angular and I’m at a loss on how to troubleshoot it and move forward. At this moment, my main objective is to simply view the URL data on my interface. Does anyone have any insights or ...

The day text function failed to return a value and instead gave back

I am having trouble figuring out where the mistake is in my function below. My goal is to retrieve the day value in string format. function getDayText(date){ var weekday = new Array(7); weekday[0]= "Sunday"; weekday[1] = "Monda ...

Troubleshooting Django Templateview: Incorporating Bootstrap Popovers into HTML tables not functioning properly

https://i.stack.imgur.com/LXHJF.pngWhen loading this template, the HTML renders correctly and the table loads successfully. However, certain cells have special pop-over attributes that do not work after the HTML is loaded via an AJAX request on the same pa ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

There appears to be an issue with the dynamic functionality of RouterLink in Angular 6

user-dashboard.html <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link" routerLink='/dashboard'>User Dashboard</a> </li> <li class="nav-item" *ngFor="let cat of categories; let i = in ...