Home > OS >  Getting error with FormGroup instance and ngIf doesn't work
Getting error with FormGroup instance and ngIf doesn't work

Time:08-13

I want to create a form on my page, but I'm getting error "Error: NG01052: formGroup expects a FormGroup instance. Please pass one in."

app-project-edit-details.component.ts

import {FormControl, FormGroup, Validators} from "@angular/forms";
...

@Component({
  selector: 'app-project-edit-details',
  templateUrl: 'project-edit-details.component.html'
})
export class ProjectEditDetailsComponent implements OnInit {
  get project(): IProject {
    return this._project;
  }

  public editForm: FormGroup;
  private projectId: number;
  private _project: IProject;

  constructor(...) {
  }

  ngOnInit(): void {
    this.projectId = this.route.snapshot.params['id'];
    this.projectService.getProjectById(this.projectId).subscribe(data => this._project = data);

    this.editForm = new FormGroup({
      projectName: new FormControl(this._project.name, Validators.required),
      ...
    });
  }
}

project-edit-details.component.html

<form [formGroup]="editForm" (ngSubmit)="onSubmit()" novalidate>
<!-- Form Inputs -->
</form>

I've also read other questions related to similar issues, but it doesn't work for me. I added *ngIf="editForm" and the error disappeared, but now I don't see my form on the page at all, although it used to be (albeit with an error), but the data in it still wasn't displayed.

CodePudding user response:

Create FormGroup instance at top of the class. Then you can use patchValue or setValue to set the values on formGroup dynamically.

import {FormControl, FormGroup, Validators} from "@angular/forms";
...

@Component({
  selector: 'app-project-edit-details',
  templateUrl: 'project-edit-details.component.html'
})
export class ProjectEditDetailsComponent implements OnInit {
  get project(): IProject {
    return this._project;
  }

  public editForm = new FormGroup({
      projectName: new FormControl('', Validators.required),
      ...
  });

  private projectId: number;
  private _project: IProject;

  constructor(...) {
  }

  ngOnInit(): void {
    
    this.projectId = this.route.snapshot.params['id'];
    this.projectService.getProjectById(this.projectId).subscribe(data => {
      this._project = data;
      //call setValue method on FormGroup and set all the values.
      this.editForm.setValue({projectName:this._project.name}...);
    });

  }
}
  • Related