Issue with Angular 5 Nested Form and Validation: Error indicating that the 'controls' property does not exist on the 'AbstractControl' type

After setting up a nested formgroup, everything seems to be working fine. However, I'm facing some challenges with properly configuring validation alerts for nested form elements.

One specific issue I encountered is an error during the build process: Property 'controls' does not exist on type 'AbstractControl'

Below is my code example:

import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Reactive Form - Nested FormGroups';

  myForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.buildForm();
  }

  buildForm() {

    this.myForm = this.fb.group({

      user : this.fb.group({
        'firstName': new FormControl('', Validators.required),
        'lastName': new FormControl('', Validators.required)
      }),

      'bio': new FormControl()
    });
  }
}

The challenge lies in setting up the validation with the div that has the class "validation-message."

<hello name="{{ name }}"></hello>

<form [formGroup]="myForm">
  <div class="my-box" formGroupName="user">
    <label>
      First Name
      <input type="text" formControlName="firstName">
      <div class="validation-message" *ngIf="!myForm.controls.user.controls['firstName'].valid && myForm.controls.user.controls['firstName'].dirty">
        This field is invalid
      </div>
    </label>
  </div>
  <div class="my-box" formGroupName="user">
    <label>
      Last Name
      <input type="text" formControlName="lastName">
    </label>
  </div>
  <div class="my-box">
    <label for="bio" class="block-me">Bio</label>
    <textarea formControlName="bio"></textarea>
  </div>
</form>

<p>
  Data from form: {{ myForm.value | json }}
</p>

Answer №1

Your TypeScript code contains a typo that needs to be corrected:

 user : this.fb.group({
    'firstname': new FormControl('', Validators.required),
    'lastName': new FormControl('', Validators.required)
  })

The field firstname should actually be camelcased in HTML:

<input type="text" formControlName="firstName">

Note that field names are case sensitive.

To fix the issue, update your TypeScript as follows:

 user : this.fb.group({
    'firstName': new FormControl('', Validators.required),
    'lastName': new FormControl('', Validators.required)
  })

UPDATE:

If you want to access the user form group in HTML, create a public property in your TypeScript file:

  public get userGroup(): FormGroup {
    return this.myForm.get('user') as FormGroup;
  }

You can now use it in HTML like this:

<div class="validation-message" *ngIf="!userGroup.controls['firstName'].valid && userGroup.controls['firstName'].dirty">
          This field is invalid
</div>

Answer №2

To resolve the issue of "Property 'controls' does not exist on type 'AbstractControl'", the solution involved separating the nested form elements in the typescript file to create its own control entity. Below is the updated code snippet:

import { Component, OnInit } from '@angular/core';
import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Reactive Forms - Nested FormGroups';

  myForm: FormGroup;
  userControl: FormGroup;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit() {
    this.buildForm();
  }

  buildForm() {

    this.userControl = this.fb.group({
      'firstName': new FormControl('', Validators.required),
      'lastName': new FormControl('', Validators.required)
    })

    this.myForm = this.fb.group({

      user : this.userControl,

      'bio': new FormControl()
    });
  }
}

HTML representation...

<hello name="{{ name }}"></hello>

<form [formGroup]="myForm">
  <div class="my-box" formGroupName="user">
    <label>
      First Name
      <input type="text" formControlName="firstName">
      <div class="validation-message" *ngIf="!userControl.controls['firstName'].valid && userControl.controls['firstName'].dirty">
        This field is invalid
      </div>
    </label>
  </div>
  <div class="my-box" formGroupName="user">
    <label>
      Last Name
      <input type="text" formControlName="lastName">
      <div class="validation-message" *ngIf="!userControl.controls['lastName'].valid && userControl.controls['lastName'].dirty">
        This field is invalid
      </div>
    </label>
  </div>
  <div class="my-box">
    <label for="bio" class="block-me">Bio</label>
    <textarea formControlName="bio"></textarea>
  </div>
</form>

<p>
  Data entered in the form: {{ myForm.value | json }}
</p>

For a functional demonstration, visit: https://stackblitz.com/edit/angular-nestedform

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

Guide to sending a collection of templates to an Angular component

As a beginner in Angular, I've been working on creating a carousel component that can be shared. The structure of this component is based on the latest version of Bootstrap and I am looking to allow templates to be injected by the caller. For instanc ...

Incorporate the Get Your Guide Widget into an Angular2 component

Currently, I am attempting to embed a "Get Your Guide" Widget within an Angular2 application. Although the script in index.html is being requested successfully, I am facing difficulties adding it to the HTML of the component. <script async defer src=" ...

I am encountering difficulties when attempting to install a specific Angular project using npm install

My old laptop was able to run my Angular project smoothly, but now I'm encountering numerous errors when trying to install it with npm on a new device. Any assistance based on the attached log would be greatly appreciated. Thank you in advance. shiva ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

The connection to Socket IO was refused due to a network error (net::

As I work on integrating socket.io into my application hosted on Azurewebsites, webapp I have the following server.js setup: var app = require('express')(); var server = require('http').createServer(app); server.listen(process.env.PO ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

What are the steps to fix errors when deploying a MEAN stack application on Heroku?

Upon building my Angular app with a Node.js API and deploying it on Heroku, I encountered an error. Despite this, the app runs smoothly with no errors when tested on my local server. Below are the logs from Heroku: C:\Users\PC>heroku logs -a= ...

Is there a kind soul out there who can shed some light on the error that pops up when I try to execute "npm run

As I embark on creating my first angular app, I started by installing it using the command npm i -g @angular/cli. However, when I attempt to create a new app with npm run ng new app, an error pops up: npm ERR! path E:\ddii\package.json npm ...

"Encountered an error in Angular: ContentChild not found

Working with Angular 5, I am attempting to develop a dynamic component. One of the components is a simple directive named MyColumnDef (with the selector [myColumnDef]). It is used in the following: parent.compontent.html: <div> <my-table> ...

Can you change the method definition of a built-in class using TypeScript?

Working with the Web Audio Api in TypeScript has presented me with a minor issue. I am trying to enhance AudioParam's prototype by adding some convenience methods that can be used on any parameter. However, I keep getting an error from the compiler st ...

The 'innerHTML' property is not present in the 'EventTarget' type

Currently, I am working with React and Typescript. My goal is to store an address in the localStorage whenever a user clicks on any of the available addresses displayed as text within p elements. <div className="lookup-result-container& ...

execute script upon changes to the DOM of the embedded vendor component

Incorporating a vendor component into MyComponent. @Component({ selector: 'my-component', template: `<vendor-component></vendor-component>` }) export class MyComponent { constructor() { } } Looking to execute some jQuery ope ...

There seems to be an issue with the functionality of Angular Material tags

Hello everyone, I am new to Angular and I am trying to create a simple list using Material Angular. However, when I tried to implement the code, all I see is a blank white web page instead of the button. Below is the code snippet I used: Template file: &l ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Generate an auto-focus Power BI report seamlessly and effortlessly

I'm working on a straightforward Microsoft Power BI example that showcases a list of employees grouped by gender. <iframe width="300" height="200" src="https://app.powerbi.com/view?r=******" ></iframe> The issue I am facing is that the ...

Tips for identifying the cause of a memory leak in browser notifications

I am looking to implement browser notifications in a browser extension. However, I have noticed that the memory usage does not decrease after closing the notification. Can someone explain why this may be happening? Allow StackOverflow show notifications i ...

The response you have received is delayed by one response

I seem to be facing an issue with my Node.js server where the response I receive is always delayed by one. The response I expect to get at the time of pressing the upload button is always received one step later. After starting the Node server, the initia ...

Angular Injection Error: Received 1 argument instead of the expected 0

Although I have already looked for a solution to this problemhere, I am still struggling to resolve the error on my own. I recently started an Ionic project and followed this link to implement authentication using Angular. Everything seemed to be working ...