Facing an Issue with Angular Reactive Form - Encountering 'formDirective is null' Error

Here is the form I have created:

<div class="container">
  <form formGroupName="checkoutForm">
    <section>
        <div class="row">
            <div class="col col-12 col-lg-8">
                <div class="row mb-4">
                    <div formGroupName="deliveryAddress">
                        <div class="col">
                            <label class="form-label">First Name</label>
                            <input id="firstName" class="form-control fw-bold" type="text" required
                                formControlName="firstName" (change)="saveToDataStore()">
                        </div>

                        <div class="col">
                            <label class="form-label">Last Name</label>
                            <input id="lastName" class="form-control fw-bold" type="text" required
                                formControlName="lastName" (change)="saveToDataStore()">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
  </form>
</div>

This is how the form is declared in the component:

export class Checkout2Component { 
  checkoutForm: FormGroup; 
  public cart;

  ngOnInit() {

    this.checkoutForm = new FormGroup({
      deliveryAddress: new FormGroup({ 
        firstName: new FormControl(''),
        lastName: new FormControl(''),
        phone: new FormControl(''),
        address1: new FormControl(''),
        address2: new FormControl(''),
        useAsBillingAddress: new FormControl(''),
      }),
      applianceDelivery: new FormGroup({ 
          deliveryDate: new FormControl(''),
          specialInstructions: new FormControl(''),
      }),
      paymentMethod: new FormGroup({ 
        // paymentType: 'new FormControl(Credit Card'),
        cardNumber: new FormControl(''),
        expMonth: new FormControl(''),
        expYear: new FormControl(''),
        CVV: new FormControl(''),
        defaultCreditCard: new FormControl(''),
      })
    });

    console.log('this.checkoutForm', this.checkoutForm.value);

    // this.initCheckoutForm();
  }

An error occurs during application run with the following message:

ERROR TypeError: this.formDirective is null ngOnInit http://localhost:4200/main-A4KJZJDC.js:14 U0 http://localhost:4200/main-A4KJZJDC.js:10 mN http://localhost:4200/main-A4KJZJDC.js:10 mw http://localhost:4200/main-A4KJZJDC.js:10 bc http://localhost:4200/main-A4KJZJDC.js:10 CR http://localhost:4200/main-A4KJZJDC.js:10 Gh http://localhost:4200/main-A4KJZJDC.js:10 w_ http://localhost:4200/main-A4KJZJDC.js:10 ER http://localhost:4200/main-A4KJZJDC.js:10 __ http://localhost:4200/main-A4KJZJDC.js:10 CR http://localhost:4200/main-A4KJZJDC.js:10 Gh http://localhost:4200/main-A4KJZJDC.js:10 w_ http://localhost:4200/main-A4KJZJDC.js:10 D_ http://localhost:4200/main-A4KJZJDC.js:10 CR http://localhost:4200/main-A4KJZJDC.js:10 Gh http://localhost:4200/main-A4KJZJDC.js:10 w_ http://localhost:4200/main-A4KJZJDC.js:10 ER http://localhost:4200/main-A4KJZJDC.js:10 __ http://localhost:4200/main-A4KJZJDC.js:10 CR http://localhost:4200/main-A4KJZJDC.js:10 Gh http://localhost:4200/main-A4KJZJDC.js:10 bR http://localhost:4200/main-A4KJZJDC.js:10 v_ http://localhost:4200/main-A4KJZJDC.js:10 _P http://localhost:4200/main-A4KJZJDC.js:10 detectChangesInAttachedViews http://localhost:4200/main-A4KJZJDC.js:10

Answer №1

The error related to formDirective cannot be replicated, but it seems that there is a misuse of the formGroup directive.

To address this issue, ensure that you properly apply the [formGroup] directive and pass the corresponding FormGroup instance within the <form> element instead of using

formGroupName="checkoutForm"
.

<form [formGroup]="checkoutForm">
  ...
</form>

Check out a demonstration on StackBlitz

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

Checkbox selection can alternate based on conditions for formgroup controls

My FormGroup named 'fruits' has been set up fruits: FormGroup = formBuilder.group({ numberOfFruits: [0,Validators.min(0)], apple: false, mangoes: false }); Here is the corresponding HTML code: <div formGroupName ...

Sharing code between Angular 8 and NodeJS 12: Best practices

Can code be shared between Angular 8 (TypeScript) and NodeJS 12? All the code is located on the same server but in separate directories /client and /server. A major issue we are facing is the duplication of regular expressions and constants across both A ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Developing web parts with Angular 2 for SharePoint 2013

Seeking advice on how to create a web part for SharePoint 2013 farm solution utilizing WCF custom Rest Services to retrieve data from the content database using server object model. I also aim to incorporate Angular 2 to consume these services within the ...

Encountering a problem when parsing a JSON file in Angular 2

When attempting to access the config.json file in my Angular2 service, I have encountered an issue. load() { return new Promise((resolve, reject) => { this.http.get('./config.json') .map(res => res.json()) ...

Issue with Angular 7 service worker caching audio files leads to range header problems in Safari browser

I am encountering an issue in my Angular application with the range request header for audio files when using Safari. When requesting audio from a server, the duration of the audio file is returned correctly. However, when requesting the audio from the ser ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

Interface for dynamic objects in Typescript

I am currently using JavaScript to create an object and would like to include an interface for the data: JavaScript: const childGroups: Children = {}; childGroups.children = []; // Adding some data childGroups.children.push(children); Interface: ...

Identifying favorited items by a user within the result list obtained from a GET request

Through a GET request, I am seeking to identify which of the outcomes have already been favorited or liked by the current user using the unique id associated with each object. There is a service in place that can determine if the user has favored an object ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...

Guidelines for implementing more rigorous type checks in TypeScript:

I am looking to enhance the code validation process and eliminate any implicit 'any' types. To achieve this, I have set "strict": true in my tsconfig.json. { "compilerOptions": { "target": "ES5", ...

What are some strategies for effectively handling numerous GraphQL modules within Apollo-Angular?

Currently at our workplace, we are in the process of developing a large project that relies on libraries created by various teams. However, we have encountered an issue with Apollo-Angular when it comes to importing multiple modules with their own graphql ...

After pressing the login button, my intention is to transition to a different page

I am relatively new to web development and working with angular. I have a login component that, upon hitting the LOGIN button, should redirect to another component on a different page. However, currently, when I click the button, it loads the data of the o ...

The current inquiry does not conform to the MultipartHttpServletRequest format

I've been encountering an error while trying to send both an image and an object from Angular to Spring Boot. The error message I keep receiving is: Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest] Below ...

Improving the clarity of Jest snapshot test logs using styled from MUI

Currently, I am working with MUI v5 along with styled components and Jest snapshot testing. I am looking for a way to improve the logs generated when a snapshot test fails. Below is an example of the component I am dealing with: const styledProperties = n ...

Defining the return type with TypeScript using the keyof accessor: A comprehensive guide

Can a function be created that utilizes keyof to access an object's property, with TypeScript inferring the return value? interface Example { name: string; handles: number; } function get(n: keyof Example) { const x: Example = {name: &apo ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Having trouble incorporating Duo Web SDK into angular application

We are currently working on incorporating Duo Two-factor authentication into our Angular application. For instructions, you can take a look at the documentation available here. The issue we are encountering is that their JavaScript file searches for an i ...

When I attempt to conceal the filter within mat-table using *ngIf, I encounter an issue where I am unable to read the property 'value' due to it being

After creating a mat-table, I encountered an issue when trying to show and hide my input filter area using a button. If I use *ngIf="showInputFilter" to hide the filter area, I receive the error message Cannot read property 'value' of u ...

Nestjs RabbitMq Microservices

I'm currently developing a microservice that is responsible for receiving messages from RabbitMQ. However, I am encountering an error message as follows: ERROR [Server] There is no matching event handler defined in the remote service. Event pattern: u ...