After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I hardcode the data and test the form without subscribing to any data. However, when I incorporate the REST API call and attempt to build the form within the subscribe method, I encounter a FormGroup error in the console multiple times:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

I suspect this issue might be related to asynchronous calls. Is there something wrong with using subscribes?

While researching a solution, I came across this post, but unfortunately, the proposed solution did not work for me as it only removed the form instead.

Please Note: I have implemented similar functionalities in other pages before and did not encounter such problems.

component.ts

import { Component, OnInit, ViewChild, ViewContainerRef, AfterContentInit } from '@angular/core';
import { Location } from '@angular/common';
import { TranslatePipe } from 'src/app/pipes/translate/translate.pipe';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { DynamicTextFieldService } from 'src/app/services/dynamic-loading/dynamic-text-field/dynamic-text-field.service';
import { DynamicDropdownService } from 'src/app/services/dynamic-loading/dynamic-dropdown/dynamic-dropdown.service';
import { DynamicTextAreaService } from 'src/app/services/dynamic-loading/dynamic-text-area/dynamic-text-area.service';
import { CustomSearchService } from 'src/app/services/search/custom-search/custom-search.service';

@Component({
  selector: 'app-knowledge-base-create',
  templateUrl: './knowledge-base-create.component.html',
  styleUrls: ['./knowledge-base-create.component.scss']
})
export class KnowledgeBaseCreateComponent implements OnInit, AfterContentInit {

  @ViewChild('f1', { read: ViewContainerRef }) f1;
  @ViewChild('f2', { read: ViewContainerRef }) f2;
  @ViewChild('f3', { read: ViewContainerRef }) f3;
  @ViewChild('f4', { read: ViewContainerRef }) f4;

  kbForm: FormGroup;
  
  projectsList: any;

  constructor(private location: Location,
    private translate: TranslatePipe,
    private dynamictextfield: DynamicTextFieldService,
    private fb: FormBuilder,
    private dynamicdropdown: DynamicDropdownService,
    private dynamictextarea: DynamicTextAreaService,
    private search: CustomSearchService) { }

  ngOnInit() {
    this.search.searchCall("PP_1_Projects", "", "", true).subscribe(
      response => {
        response = response.records;
        this.projectsList = response;
        this.buildForm();
      },
      error => {
        console.log(error);
      }
    );
  }

  ...
  
}

component.html

<div>
  <app-toolbar></app-toolbar>
  <app-side-nav></app-side-nav>
  <div class="container-fluid">
    <app-button description="{{ 'pages[knowledge_base][buttons][go_back]' | translate }}" class="btn btn-danger btn-md custom" (callFunction)="goBack()"></app-button>
    <div class="card-group">
      <div class="card p-4">
        <form [formGroup]="kbForm">
          <h2 class="col-md-6">Create New Knowledge Base Article</h2>
          <div class="col-md-3">
            <div #f1 class="input"></div>
            <div #f2 class="input"></div>
            <div #f3 class="input"></div>
          </div>
          <div class="col-md-6">
            <div #f4 class="input"></div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

Answer №1

Discovered a solution to the issue - the this.buildf2(); function was relying on the data stored in projectsList from the response, rather than adding this.buildForm(); to the response group directly. So, instead of including this.buildForm(); in the response group, I introduced a new function that resolved the problem. This modification successfully rendered the div with the updated response.

Here is how it was implemented:

// Relevant imports and component declaration
@Component({
  selector: 'app-knowledge-base-create',
  templateUrl: './knowledge-base-create.component.html',
  styleUrls: ['./knowledge-base-create.component.scss']
})
export class KnowledgeBaseCreateComponent implements OnInit, AfterContentInit {

 // Previously defined ViewChild elements
  
  projectsList: any;

  kbForm: FormGroup;

  constructor(private location: Location,
    private translate: TranslatePipe,
    private dynamictextfield: DynamicTextFieldService,
    private fb: FormBuilder,
    private dynamicdropdown: DynamicDropdownService,
    private dynamictextarea: DynamicTextAreaService,
    private search: CustomSearchService) { }

  ngOnInit() {
    this.buildForm(); // Removed direct call from here, replaced with buildForm()
  }

  buildForm() {
    this.kbForm = this.fb.group({
      'f1': ['', Validators.required],
      'f2': ['', Validators.required],
      'f3': ['', Validators.required],
      'f4': ['', Validators.required]
    })
  }

  ngAfterContentInit() {
    this.buildf1();
    this.buildf3();
    this.buildf4();
    this.retrieveProjectData(); // Added function here, now renders correctly
  }

  // New function created to retrieve project data and trigger necessary actions
  retrieveProjectData() {
    this.search.searchCall("PP_1_Projects", "", "", true).subscribe(
      response => {
        response = response.records;
        this.projectsList = response;
        this.buildf2();
        console.log(response);
      },
      error=>{
        console.log(error);
      }
    )
  }

  // Existing methods for building form fields...
  
  // Helper method for accessing form controls easily
  get form() {
    return this.kbForm.controls;
  }


}

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

Having trouble with i18n types not functioning correctly in Typescript and Nuxt?

I am currently utilizing NuxtJS/i18n with TypeScript and have included its types in my TS config: { "compilerOptions": { "types": [ "@nuxt/types", "@nuxtjs/i18n", ] } } However, when attempti ...

Module 'ngx-bootstrap' not found in project

My application is encountering an issue with ngx-bootstrap where the module can no longer be detected unless the path is specified. For instance: import { BsModalService, BsModalRef } from 'ngx-bootstrap'; results in "Cannot find module ' ...

Leverage the power of the MEAN stack with Angular 2 to seamlessly retrieve data from multiple APIs

Using angular2, nodejs, expressjs, and mongodb for development. I need all APIs to fetch data and display it on an HTML page. Below is the code snippet from my .ts file. view image description here All APIs have been tested and are s ...

Combining cells for certain entries in an Angular data table

Just starting to learn angular, and here's the scenario I'm dealing with: I have a table consisting of 10 columns. Let's say column 4 contains different status categories like children, teen, young, adult, and senior. When displaying all ...

Utilizing objects as values with `react-hook-form`

About the Issue I'm facing an issue with a component that utilizes an object as its value. My goal is to integrate this component with react-hook-form The challenge arises when react-hook-form considers my object as a nested form control Background ...

Unable to retrieve the reflective metadata of the current class instance

Is it possible to retrieve the reflect-metadata from an instance of a class? The documentation provides examples that suggest it should be achievable, but when I attempt to do so, I receive undefined as a result. Strangely enough, when I request the metada ...

Issue detected in loading ./styles.css in Angular 6

I'm a beginner with Angular 6 and encountered this error in my project: ERROR in multi ./node_modules/bootstrap/dist/css/bootstrap.min.css ./styles.css Module not found: Error: Can't resolve 'C:\Users\User\e-CommerceWebsite& ...

Pagination in Laravel using Angular 5

Currently experiencing pagination issues in an Angular5 and Laravel5 project. The JSON values are as follows: { "products": { "current_page": 1, "data": [ ... ], "first_page_url": "http://localhost:8000/api/ ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

What is the best method to publish my npm package so that it can be easily accessed through JSDelivr by users?

I've been working on creating an NPM package in TypeScript for educational purposes. I have set up my parcel configuration to export both an ESM build and a CJS build. After publishing it on npm, I have successfully installed and used it in both ESM-m ...

A mistake was made: The template contains errors stating that 'app-my-profile' is an unknown element

I encountered an error message: "Uncaught Error: Template parse errors: 'app-my-profile' is not a known element," while working on setting up my profile service. import { BrowserModule } from '@angular/platform-browser'; import { NgM ...

"Implementing a date picker in your Ionic 5 app: A step-by-step

How can I integrate a date picker similar to the Angular Material Date picker into my Ionic 5 application? I prefer not to use the native ion-datetime component due to limitations such as incomplete calendar display and lack of support for alternative ca ...

An error was encountered while trying to use the 'export' token in lodash-es that was not

Transitioning from lodash to lodash-es in my TypeScript project has been a challenge. After installing lodash-es and @types/lodash-es, I encountered an error when compiling my project using webpack: C:\..\node_modules\lodash-es\lodash. ...

What is the best way to access and read all @input elements within an Angular component?

Looking to retrieve all properties marked with the @Input() decorator in an Angular component. Attempts using reflect and reflect-metadata have been unsuccessful. Any suggestions on how to achieve this functionality? ...

Next.js Troubleshooting: Unexpected Issue with 'use client' Triggering Error in React Client Component

Keeping it simple, here is a useState function that I am using: 'use client' import {useState} from 'react'; const Home = () => { const [fruit, setFruit] = useState('apple'); return ( & ...

Is it possible for changes made to an object in a child component to be reflected in the parent component

When passing an object to the child component using , how can we ensure that changes made to a specific property in the object within the child component are visible in the parent component? In my understanding, changes would not be reflected if we were p ...

Can a ternary operator be used within an index type query when extending a partial type?

Can anyone provide a detailed explanation of the process unfolding in this snippet? I'm having trouble grasping how this code leads to a type declaration. type ModalErrors = Partial< { [key in keyof InputGroup]: InputGroup[key] extends Speci ...

I am currently working to resolve this particular wildcard issue with the help of TypeScript

I've been working on solving the wildcard problem with TypeScript, but I'm running into issues with some of the test cases I've created. Here's a brief overview of how the code operates: A balanced string is one where each character ap ...

Tips for accessing Firebase document fields with Angular Firestore (version 7)

My current task involves retrieving a Firebase document property based on the specified model: After successfully locating a document with this code snippet: //Users - collection name, uid - document uid. I am attempting to access the isAdmin property u ...

Should Angular libraries be developed using Typescript or transpiled into JavaScript?

Currently, I am in the process of developing a library that will be available as an Angular module through npm. The library itself has been written using typescript. Everything was functioning perfectly up until Angular version 5.0.0, but after this update ...