Troubleshooting engine malfunction in Angular 9 caused by FormGroup usage

Here is a sample code snippet of a component:

export class BaseFormComponent implements OnInit {
  basicFormGroup: FormGroup;
  constructor(
    protected basicProviderService: BasicProviderService,
    protected formBuilder: FormBuilder,
    protected dialog: MatDialog,
    protected spinner: NgxSpinnerService
    ) {
    this.basicFormGroup = this.formBuilder.group({
      name:[''],
      note: ['', Validators.required],
      description: ['', Validators.required]
    });
  }
}

Below is the template code for the component:

<h3><span>Basic form data</span></h3>
<mat-divider></mat-divider>
<form *ngIf="true" [formGroup]="basicFormGroup">
<!-- content omitted-->
</form>

A test scenario has been created as shown below:

fdescribe('BasicFormComponent', () => {
  let component: BasicFormComponent;
  let fixture: ComponentFixture<BasicFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [BasicFormComponent],
      imports: [
        FormsModule,
        MatDialogModule,
        MatAutocompleteModule,
        MatSnackBarModule,
        MatExpansionModule,
        MatStepperModule,
        MatFormFieldModule,
        TextFieldModule,
        MatInputModule,
        MatDatepickerModule,
        MatNativeDateModule,
        MatListModule,
        MatSelectModule,
        HttpClientTestingModule,
        RouterTestingModule,
        BrowserAnimationsModule,
        CoreModule
      ],
      providers: [
        { provide: BasicProviderService, useClass: BasicProviderServiceStub }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicFormComponent);    
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

An error occurs during testing when the createComponent method is called:

HeadlessChrome 80.0.3987 (Windows 10.0): BasicFormComponent should create FAILED
        Error: NodeInjector: NOT_FOUND [ControlContainer]
            // Error details omitted for brevity
        Expected undefined to be truthy.
            // More error logs here
HeadlessChrome 80.0.3987 (Windows 10.0.0): Executed 1 of 181 (1 FAILED) (0 secs / 0.293 secs)

Several troubleshooting steps were attempted:

  • Test succeeds with ngIf='false', but fails with any form element present
  • Replacing [formGroup]='basicFormGroup' with [formGroup]='undefined' causes the test to fail

The culprit might be related to missing dependencies in the app.module.ts file.

The issue seems to revolve around the application not being able to locate the necessary forms abstraction.

What could potentially trigger this problem?

Answer №1

When working with reactive forms, it is necessary to import the ReactiveFormsModule, whereas template-driven forms require the use of FormsModule.

In this case, the formGroup directive is being used, which belongs to reactive forms, so importing ReactiveFormsModule is essential.

To learn more about the distinction between these two types of forms, refer to the Angular documentation.

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

Leveraging the Cache-Control header in react-query for optimal data caching

Is it possible for the react-query library to consider the Cache-Control header sent by the server? I am interested in dynamically setting the staleTime based on server instructions regarding cache duration. While reviewing the documentation, I didn&apos ...

Unable to retrieve data from database using Angular 4

I am currently working with Angular 4 and using a MySQL database. This is my service: service.ts getData(){ return this.http.get('http://example/users.php').map(res=>{ return res.json(); }).catch(err=>{ return err.jso ...

Observable emitting individual characters instead of the entire string in an optional parameter of an activated route

Within an Angular component, I have a method with the following content: this.route.paramMap.pipe( switchMap((params: ParamMap) => { let fooValue = params.get('selectedid'); console.log("inside switch map with value as " + ...

After clicking on the "Delete Rows" button in the table, a white color suddenly fills the background in Angular Material

When the dialog box pops up, you'll see a white background color: https://i.stack.imgur.com/EflOx.png The TypeScript code for this action can be found in config-referrals.component.ts openDialog(action, obj) { this.globalService.configA ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Having trouble fetching information from a JSON file stored in a local directory while using Angular 7

I am currently experiencing an issue with my code. It works fine when fetching data from a URL, but when I try to read from a local JSON file located in the assets folder, it returns an error. searchData() { const url: any = 'https://jsonplaceholde ...

Angular2 Directive that Duplicates a Group of <tr> Elements

How can I build a component that generates HTML based on this data and HTML code? The <head> and <tbody> sections are projected, and I understand how to project multiple elements. However, I am unsure of how to repeat the projected <tr> i ...

Could it be that the TypeScript definitions for MongoDB are not functioning properly?

Hello everyone, I'm facing an issue with getting MongoDB to work in my Angular 4 project. In my code, I have the db object as a client of the MongoClient class: MongoClient.connect('mongodb://localhost:27017/test', (err, client) => { ...

Implementing cursor-based pagination in Next.js API Route with Prisma and leveraging the power of useSWRInfinite

I am working on implementing cursor-based pagination for a table of posts using Next.js API Route, Prisma, and useSWRInfinite. Currently, I am fetching the ten most recent posts with Prisma in a Next.js API Route and displaying them using useSWR, sorted b ...

Tips for managing the error message "The key 'myOptionalKey' is optional in the 'myObject' type but necessary in the '{...}' type"

Issue I'm currently working on making a sortable table using a sample table component from Material-UI. I encountered an error when I included an optional key in the Data object. It seems that the type definition in the getComparator function does no ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

Testing an angular function that requires multiple arguments in its constructor

My goal is to conduct unit tests on functions within a component. The constructor for this component requires four arguments. Initially, I attempted to simply set the arguments as (new AClass, new BClass, new CClass, new DClass); however, some of these cla ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Establishing the parameters for a list that is not empty using a specific data type

Is it feasible to establish a non-empty list within TypeScript's type system? While I am aware that it is possible to define a list with a specific number of elements, similar to a Tuple: type TwoElementList = [number, number]; This approach is limi ...

Is it possible to conceal dom elements within an ng-template?

Utilizing ng-bootstrap, I am creating a Popover with HTML and bindings. However, the ng-template keeps getting recreated every time I click the button, causing a delay in the initialization of my component. Is there a way to hide the ng-template instead? ...

Experimenting with a Jest test on an express middleware

I'm currently faced with a challenge in testing my controller (express middleware) using Jest. To better illustrate the issue, I will share the code snippet below: import request from 'utils/request'; import logger from 'config/logger& ...