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

How to Pass a JSON Object to a Child Component in Angular and Display It Without Showing "[Object

Need help with my API call implementation. Here's a snippet from my Input component: Input.html <form (submit)="getTransactions()"> <div class="form-group"> <label for="exampleInputEmail1"></label> <input type="t ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Executing the command "node-gyp rebuild" will produce a build log in the file "build_log.txt", and any errors will be redirected

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e5e7e3d0a9bea1a4bea0">[email protected]</a> install /var/www/html/my-app/node_modules/uws node-gyp rebuild > build_log.txt 2>&1 || exit 0 Error: There ...

Contrasting the double dash without any arguments versus the double dash with a specific argument, such as "no-watch."

For instance, when attempting to run unit tests for an Angular app, the following command is used: npm run test -- --no-watch --browsers=ChromeHeadlessCI I know that two dashes (--) are required to pass arguments into the npm script. However, I'm con ...

Issue: subscribe function is not definedDescription: There seems to be an

I'm currently trying to retrieve a value from an array based on a specific element, and then finding the exact matching element. Unfortunately, I've encountered an error with this.getProduct(name1: string) function even though I have already impo ...

Is it possible to reset or recycle SoftAssert for repeated use?

When writing code for each @Test method, I am aware that a new instance of SoftAssert should be used. But is there a way to reset or reuse an already existing instance? And how can I ensure memory is freed up after every test case? If I have 1000 test ca ...

Sending data to server using Angular's POST request

Even though I am attempting to transmit data to a server, it doesn't seem to be arriving. createUserProfile(email: string, password: string) { let userData = { email, password }; let authHeaders = new HttpHeaders({ 'Content-Type&a ...

What are the benefits of pairing Observables with async/await for asynchronous operations?

Utilizing Angular 2 common HTTP that returns an Observable presents a challenge with nested Observable calls causing code complexity: this.serviceA.get().subscribe((res1: any) => { this.serviceB.get(res1).subscribe((res2: any) => { this.se ...

When converting an NgbDate to a moment for formatting needs, there is a problem with the first month being assigned as 0 instead of 1

I am encountering a challenge with my Ngb-Datepicker that allows for a range selection. To customize the output format, I am using moment.js to convert the NgbDate into a moment object (e.g., Wed Jan 23). One issue I encountered was that NgbDates assign J ...

Creating nested Array objects in a table format in Angular 2 without using a nested table and ensuring that columns remain aligned

I'm currently working on generating a table with nested Array objects. Unfortunately, using nested tables is causing alignment issues between the header of the outer table and the columns in the inner table. Here's an example of the classes I&ap ...

Why does the error message "DeprecationWarning: 'originalKeywordKind' deprecated" keep popping up while I'm trying to compile my project?

Upon completing the compilation of my project, I encountered the error message provided below. What does this signify and what steps can I take to resolve it? - info Linting and checking validity of types DeprecationWarning: 'originalKeywordKind' ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

The modal functionality in AngularJS doesn't seem to be functioning properly

I am currently working on an Angular application where I want to implement a button that, when clicked, will open a pop-up window displaying a chart. Below is the button code: <div style="padding-top:50px;padding-left:10px;"> <button type="butto ...

Leveraging Angular and HTML to efficiently transfer the selected dropdown value to a TypeScript method upon the user's button click

I am experiencing difficulty accessing the .value and .id properties in {{selectItem}} in order to send them back to the typescript for an HTTP post at a later time. Although there are no specific errors, I have encountered exceptions and have tried search ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

Customizing Angular with SASS Theming

After coming across the query How can switchable themes be implemented in SCSS?, particularly the second response which drew inspiration from this insightful Medium post, I decided to try implementing themes using SASS on my project. Unfortunately, I hav ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...