Issue: The formGroup function requires a valid instance of a FormGroup. Make sure to provide one. Additionally, there is an error due to trying to access properties of an undefined object

As I attempt to retrieve and modify the employee details, I am encountering issues. While I am able to get the correct values for the details in the form, when it comes to editing, I am facing errors as described below:

Error: formGroup expects a FormGroup instance. Please pass one in. TypeError:Cannot read properties of undefined (reading 'setValue') TypeError: Cannot read properties of undefined (reading 'get')

The issue seems to be with setting values using getFormContent() function in the edit form.

If someone could guide me on understanding these errors and provide assistance on how to proceed, I would greatly appreciate it. Thank you.

export class AddEditEmpPersonalComponent implements OnInit {

  form: FormGroup;
  empOfficialDetails: Employee;
  employeePersonalDetails : EmployeePersonalDetails;
  editMode: boolean = false;
  employeeCreatedOrUpdated : boolean = false;
  formTitle : string;
  successMessage: string;
  employeeId : string;
  selectedFile: File = null;
  url : any;

  constructor(
    private fb: FormBuilder, 
    private employeeService : EmployeeService,
    private route : ActivatedRoute) {
      var id = this.route.snapshot.paramMap.get('id');
      this.employeeId = id;
              
              
      this.employeeService.getEmployeePersonalDetails(this.employeeId)
        .subscribe(data => {
          this.employeePersonalDetails = data;
          if (this.employeePersonalDetails = null)
          {
            alert("create");
            this.editMode = false;
            this.createForm();
            this.formTitle ="Add Employee Personal Details";
            this.successMessage = "Employee Personal Details Added";
            this.employeeCreatedOrUpdated = true;
          }
          else
          {
            alert("edit")
            alert("hi");
            alert(this.employeePersonalDetails.id);
            alert(this.employeePersonalDetails.nationality);
            alert("hello");
            this.editMode = true;
            this.getFormContent();
            this.formTitle ="Update Employee Personal Details";
            this.successMessage = "Employee Personal Details Updated";
            this.employeeCreatedOrUpdated = true;
            //edit
          }
        }
      )
  }

This is the create form

createForm(){
  this.form = this.fb.group({
      
    "id": this.employeeId, // why does this say unknown property
    "fullName": this.empOfficialDetails.firstName+ " " +this.empOfficialDetails.middleName + " " + this.empOfficialDetails.lastName,
    "photo": [''],

    "dateOfBirth": [''],
    "nationality": [''],
    ...........
  })
}

This is the getFormContent() which is supposed to prefill the data in the form for edit

getFormContent(){
  this.form.setValue({ 
    fullName: this.employeePersonalDetails.fullName || '',
    photo:this.employeePersonalDetails.photo || '',
    bankName: this.employeePersonalDetails.bankName || '',
    branch: this.employeePersonalDetails.branch  || '',
    .........
  })
} 

I can see the proper values in the Network tab

However, The following errors are being displayed

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

      Example:

      
  <div [formGroup]="myGroup">
    <input formControlName="firstName">
  </div>

  In your class:

  this.myGroup = new FormGroup({
      firstName: new FormControl()
  });
    at missingFormException (forms.js:1497)
    at FormGroupDirective._checkFormPresent (forms.js:5520)
    at FormGroupDirective.ngOnChanges (forms.js:5293)
    at FormGroupDirective.rememberChangeHistoryAndInvokeOnChangesHook (core.js:1498)
    at callHook (core.js:2536)
    at callHooks (core.js:2495)
    at executeInitAndCheckHooks (core.js:2446)
    at refreshView (core.js:9480)
    at refreshEmbeddedViews (core.js:10590)
    at refreshView (core.js:9489)
defaultErrorLogger @ core.js:6479
handleError @ core.js:6527
(anonymous) @ core.js:29691
invoke @ zone.js:372
run @ zone.js:134
runOutsideAngular @ core.js:28572
tick @ core.js:29691
(anonymous) @ core.js:29539
invoke @ zone.js:372
onInvoke @ core.js:28673
invoke @ zone.js:371
run @ zone.js:134
run @ core.js:28527
next @ core.js:29538
__tryOrUnsub @ Subscriber.js:183
next @ Subscriber.js:122
_next @ Subscriber.js:72
next @ Subscriber.js:49
next @ Subject.js:39
emit @ core.js:25936
checkStable @ core.js:28595
onHasTask @ core.js:28690
hasTask @ zone.js:426
_updateTaskCount @ zone.js:447
_updateTaskCount @ zone.js:274
runTask @ zone.js:195
drainMicroTaskQueue @ zone.js:582
invokeTask @ zone.js:491
invokeTask @ zone.js:1600
globalZoneAwareCallback @ zone.js:1626

core.js:6479 ERROR TypeError: Cannot read properties of undefined (reading 'get')
    at FormGroupDirective.addControl (forms.js:5346)
    at FormControlName._setUpControl (forms.js:5929)
    at FormControlName.ngOnChanges (forms.js:5874)
    at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.js:1498)
    at callHook (core.js:2536)
    at callHooks (core.js:2495)
    at executeInitAndCheckHooks (core.js:2446)
    at refreshView (core.js:9480)
    at refreshEmbeddedViews (core.js:10590)
    at refreshView (core.js:9489)


core.js:6479 ERROR TypeError: Cannot read properties of undefined (reading 'setValue')
    at AddEditEmpPersonalComponent.getFormContent (add-edit-emp-personal.component.ts:146)
    at SafeSubscriber._next (add-edit-emp-personal.component.ts:58)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)

Answer №1

Before the HTML is rendered, the form in the existing code was not initialized.

form: FormGroup;

The form instance is only created after receiving an Observable from the employeeService.

this.employeeService
      .getEmployeePersonalDetails(this.employeeId)
      .subscribe((data) => {
        this.employeePersonalDetails = data;
        if ((this.employeePersonalDetails == null)) {
          ...
          this.createForm();
          ...
        } else {
          ...
          this.getFormContent();
          ...
        }
      });

Solution

You need to initialize the form first before rendering the HTML.

.component.ts

constructor(
  private fb: FormBuilder,
  private employeeService: EmployeeService,
  private route: ActivatedRoute
) {
  var id = this.route.snapshot.paramMap.get('id');
  this.employeeId = id;

  this.initForm();

  this.employeeService
    .getEmployeePersonalDetails(this.employeeId)
    .subscribe((data) => {
      ...
    });
}

initForm() {
  this.form = this.fb.group({
    id: ['']
    fullName: [''],
    photo: [''],

    dateOfBirth: [''],
    nationality: [''],
  });
}

Visit StackBlitz for a demonstration

Note:

It is recommended to move all initialization tasks to the ngOnInit() method, as suggested by @PardeepJain's answer on the Difference between Constructor and ngOnInit.

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

Displaying the value in Angular without triggering a change

How can I display the initial value of a variable without updating it when the value changes? <span>{{value}}</span> I want the span to only show the initial value and not update when the value changes. Is there a way to accomplish this? ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

What is the reason behind having two modules within the same file for this authentication module?

While delving into the ngrx implementation in the example app on GH, I stumbled upon an intriguing question. Why does the linked file contain two modules instead of just one? What prompted the developer to opt for this structure? Check out the Github link ...

Angular 6 has numerous modules that have similar names but vary only in their letter casing

After running ng serve, I encountered an error that has me stumped. Everything was working fine with the new service I created until suddenly it all crashed :( I tried troubleshooting everything possible but to no avail. Even Google didn't provide any ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

How do I go about creating shades when working with material theming?

Hello everyone! I am interested in developing a unique theme with Angular Material theming, incorporating my own set of three colors. Typically, the Angular Material themes are defined with shades like this: $mat-red: ( 50: #ffebee, 100: #ffcdd2, 20 ...

What is the best way to adjust the width of Bootstrap columns to match the length of the longest column in

The Challenge In my task, I am dealing with a list featuring two columns. The issue that I am encountering is the desire for the left column to begin precisely where the longest column on the left ends. Presently, it initiates directly after the first col ...

Learn the process of presenting data in an HTML file using TypeScript within AngularJS 8

I recently made a GET method API call in my app.component.ts file: export class UsersComponent implements OnInit { usersdatainfo : any; constructor( private http: HttpClient ) { this.http.get(this.url).subscribe( userdata => { ...

Utilizing AES encryption in C# and decrypting it in Angular, converting it from a byte[] / number array with the help

I am looking to securely encrypt and decrypt a byte[] in a C# API endpoint, then convert the decrypted document to base64 for viewing in a PDF viewer within an Angular 14 app. I came across this helpful guide on Stack Overflow [https://stackoverflow.com/q ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

`Incorporating CSS Pseudo-elements to Customize Angular Font Awesome Icons Issue`

I successfully integrated @fortawesome/angular-fontawesome into my Angular 7 application by following the instructions provided on https://www.npmjs.com/package/@fortawesome/angular-fontawesome. Although I am able to use the icons directly, I am facing di ...

Leveraging a custom pipe along with a ternary operator in an *ngFor loop

Having troubles with a custom pipe using ternary operator in *ngFor and encountering errors. Seeking assistance to resolve the issue. Here is the HTML code snippet: <div *ngFor="let x of y | limitTo: y.limit ? y.length : 10"> The truncate.pipe.ts ...

Issue with TypeORM custom repository not successfully overriding the createQueryBuilder function

I have successfully implemented database i18n for TypeORM in theory. Now, I am looking to override built-in repository methods to incorporate i18n by intercepting them and adding a query. However, I am facing difficulties with overriding the createQueryBui ...

Sending both headers and body in Angular using HttpClientWould you like any further assistance with

When attempting to send user information and a JWT token to my server, I am encountering an issue where the server is printing 'undefined' when I try to access the request body. Below is the Angular code I am using: subscribeToPlan(jwtToken: ...

Endlessly calling a function binding to a property

I've come across a very peculiar issue in my Angular application. Imagine I have a simple example.component.ts @Component({ moduleId: module.id.toString(), selector: 'example', templateUrl: 'example.component.html', ...

Storing information retrieved from the API for use in different modules

Trying to extract data from a WEB API service using Angular 8 has been quite challenging for me. A service I created makes the API call: return this.http.get<UserSession>(uri) .pipe(map((json: UserSession) => this.EntryFormAdapter(json))); Th ...

Difficulty deploying Angular app with Firebase hosting

I've encountered an issue while trying to deploy my Angular application on Firebase hosting. After the loader, it displays nothing and an error is shown in the console. TypeError: Object(...)(...).firestore is not a function The application works pe ...

Leveraging Angular2+ components across various modules

Bringing in a component called "TemperatureComponent" into a module named "DashboardModule" and defining + exporting it there: import { TemperatureComponent } from './temperature/temperature.component'; import { TemperatureDraggerComponent } from ...

Struggling with the @typescript-eslint/no-var-requires error when trying to include @axe-core/react? Here's a step-by

I have integrated axe-core/react into my project by: npm install --save-dev @axe-core/react Now, to make it work, I included the following code snippet in my index.tsx file: if (process.env.NODE_ENV !== 'production') { const axe = require(&a ...

Tips for changing the color of an MUI 5 checkbox and label when hovering

I am looking to create a checkbox enclosed in a wrapper with a label. The goal is to change the color of everything inside the wrapper when it is hovered over. Here is an example image: https://i.sstatic.net/T3OU5.png Below is the code I have attempted: ...