1

This is not the usual module-related. Because I'm using Angular v16, standalone component, no module is required.

TS

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

@Component({
  selector: 'app-x',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],  // same err with or without  FormsModule, ReactiveFormsModule
  templateUrl: './x.component.html',
  styleUrls: ['./x.component.scss']
})
export class XComonponent
{
  public fg1?: FormGroup;
  // rest of the code
}

HTML

<form [formGroup]="fg1">formGroup is highlighted as error</form>

This component is generated with --standalone switch in a legacy Angular project still using @NgModule in app.module.ts.

Jeb50
  • 6,272
  • 6
  • 49
  • 87

2 Answers2

0

In an application bootstrapped for standalone, you have to pull in the form providers with something like this:

bootstrapApplication(AppComponent, {
    providers: [
        importProvidersFrom(FormsModule, ReactiveFormsModule), ...]

If you aren't using standalone bootstrapping, I assume you still need to pull in the forms providers in your main NgModule.

DeborahK
  • 57,520
  • 12
  • 104
  • 129
0

What I did to fix the issue was remove FormsModule, but keep ReactiveFormsModule in the imports of the @Component. Also adding a constructor to initializethe formgroup. Here is the working stackblitz link.

Here is the pasted code:

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  FormBuilder,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello from {{name}}!</h1>
    <a target="_blank" href="https://angular.io/start">
      Learn more about Angular 
    </a>
    <form [formGroup]="formGroup">form group example
  `,
  imports: [CommonModule, ReactiveFormsModule],
  standalone: true,
})
export class App {
  name = 'Angular';
  formGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    this.formGroup = this.fb.group({
      // your form controls go here
    });
  }
}

bootstrapApplication(App);
Corey Sutton
  • 767
  • 5
  • 19