What could be causing the 'controls' property to be undefined when using form: FormGroup in an Angular 11 component?

Just diving into Angular 11 and getting to grips with TypeScript.. I'm trying to access the 'controls' property in a specifically defined 'FormGroup' variable. But for some reason, it keeps saying that the property is undefined...

send(form: FormGroup): void{
    let jsonModel = {
      materialNum: form.controls['materialNum'].value,
    };

    let jsonModelRaw: string = JSON.stringify(jsonModel);
    //...
}

https://i.sstatic.net/mKzKb.png

Here's what I have declared:

import { FormBuilder, FormControl, FormGroup, NgForm, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms';

HTML for the Component:

  <mat-vertical-stepper [linear]="isLinear" #stepper>
    <mat-step [completed]="stepOneDone" [stepControl]="newMaterialFormGroup">
      <form [formGroup]="newMaterialFormGroup"
            name="newMaterialForm"
            #newMaterialForm="ngForm"
            (ngSubmit)="send(newMaterialFormGroup.value)">
        <ng-template matStepLabel>Fill out new material form</ng-template>
        <mat-form-field>
          <mat-label>Material #</mat-label>
          <input matInput placeholder="Material ID" formControlName="MaterialNum" required>
        </mat-form-field>

Answer №1

Shoutout to @miqh for pointing out my mistake. I realized that in the HTML code, I was passing the FormGroup's value as an argument instead of the actual object itself. Essentially, I was passing in raw JSON data.

Therefore, the line

(ngSubmit)="send(newMaterialFormGroup.value)">
should be revised to
(ngSubmit)="send(newMaterialFormGroup)">

By making this change, I am now passing the object itself, which allows me to successfully access the controls property.

However, the lingering question is... Why didn't TypeScript catch this error even though I clearly specified that the parameter was of type FormGroup and have strong typing enabled?

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

Issue in TypeScript: The module "*.svg" does not have a component that is exported named "ReactComponent"

I'm attempting to bring in an .svg file as a React component using TypeScript. As per the React documentation, the process should look like this: import { ReactComponent as Icon } from './Icon.svg'; Referring to the TypeScript documentati ...

Turning ngIf from false to true upon clicking the back button

I added an ngIf directive to hide a button on click and then move on to the second component. In the second component, I included a back button to return to the first component. However, when I click "back" to go to the first component, the ngIf remains fa ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...

Global installation of Node modules

How do I reference globally installed node modules? For example, if I have a package.json file and I choose to install all the node modules listed in it globally (located at C:\Users\MyaccountName\AppData\Roaming\npm), how can I ac ...

Prevent the 'unbound function' ESLint warning when supplying a static method reference to a superclass constructor in TypeScript

Looking to solve a technical problem in my code. I have a class that needs to call its superclass using a function passed as an argument. I specifically want to pass a static function from the same class: export abstract class ChildAdapter extends Adapter{ ...

What is the benefit of utilizing ngSubmit over just using a basic button and function?

Lately, I've been pondering whether to utilize ngSubmit or simply bind a (click)="submit()" on a button. There's been much debate about using submit and ngSubmit, but is it necessary to rely on the traditional HTML submit method? Particularly wh ...

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

In Safari, Angular 6 fails to display data points when a component is routed to the d3/event-drops

After creating a test app to replicate the current issue, I have come across an interesting problem. Here is the link to the codebase: https://github.com/mohammadfarooqi/event-drops-d3-test-app. You can also view a sample demo deployed (recommended in saf ...

Navigating through observable arrays

I am looking to create a dynamic display of documents retrieved from Firestore. My goal is to initially show 5 documents and then have a "Load more" button that will fetch an additional 5 documents each time it is clicked. Implementing this with a static ...

Typescript interface created specifically for React Higher Order Component Props

Consider the React HOC provided below which adds sorting state to a component: import React, {Component, ComponentClass, ComponentType} from 'react' interface WithSortState { sortOrder: string } interface WithSortInjectedProps { sortO ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: https://i.sstatic.net/RoGER.png The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should ...

Converting ts files to js: A comprehensive guide

I am looking for a way to transform my TypeScript files into JavaScript files smoothly. The conversion process goes well with the command: nodemon --watch assets/ts --exec tsc assets/ts/*.ts --outDir assets/js However, I have encountered an issue where im ...

What is the best way to avoid special characters in Angular Date pipe?

I have a query that might have been addressed on SO before. However, none of the solutions provided so far have helped me. Therefore, I am posting this question in hopes of finding an answer: I am trying to format a string and escape the h letter within i ...

Is there a way to dynamically exclude files from the TypeScript compiler?

Currently, I am in the process of setting up a node/typescript server for a real-time application. Both my server and client are located within the same folder. My goal is to exclude "src/client" from the typescript compiler when executing the "server:dev ...

ngx-datatable detail row failing to expand properly

I am striving to develop an ngx-datatable component that can be utilized universally for consistent styling and functionality. Although most features are working correctly, I'm struggling to understand why the details row isn't expanding as expe ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

Exploring Ionic 2: Utilizing Service and modalCtrl for enhanced functionality

I am relatively new to using Ionic 2. Recently, I created a service that contains all my filters (ModalCtrl) with custom search input and checkboxes. I am passing parameters between them but I am unsure of how to keep the service active and waiting for the ...

Discover the steps to dynamically alter the inclusion of the Bootstrap CSS file within an Angular project

I manage a multi-language website in both English (EN) and Arabic (AR). Currently, I am utilizing Bootstrap CSS from a CDN and adjusting the CDN link based on the selected language. index.html <!DOCTYPE html> <html lang="en"> <h ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

Tips for transmitting data from Dart to Typescript Cloud functions, encountering the UNAUTHENTICATED error code

Snippet of Dart code with token passed to sendToDevice: Future<void> _sendNotification() async { CloudFunctions functions = CloudFunctions.instance; HttpsCallable callable = functions.getHttpsCallable(functionName: "sendToDevice"); callable.c ...