This is not the usual module-related issue. 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
.
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);