Search code examples
angulartypescriptangular-forms

Error: formGroup expects a FormGroup instance. Please pass one in. - Angular 10 Error


I have problem with error: Error: formGroup expects a FormGroup instance. Please pass one in. With this error I have parallel other error: Cannot read property 'get' of undefined. I tried resolved this errors but still without results

My code:

component.html

<form [formGroup]="captchaForm" (submit)="submit()" class="form">

  <mat-form-field appearance="fill" class="form-group">
    <mat-label>Site Code</mat-label>
    <input
      matInput
      id="handle"
      type="text"
      formControlName="handle"
      autofocus required
    >
  </mat-form-field>

  <mat-form-field appearance="fill" class="form-group">
    <mat-label>Code from image</mat-label>
    <input
      matInput
      id="token"
      type="text"
      formControlName="token"
      autofocus required
    >
  </mat-form-field>

  <button mat-raised-button class="form-button" color="primary" type="submit">Submit</button>

</form>

component.ts

captchaForm: FormGroup;
captchaData: Captcha;
dataDisplay = false;
    
constructor(
    public formBuilder: FormBuilder,
private captchaService: CaptchaService,
){}

ngOnInit(): void {
this.getCaptcha();
this.captchaForm = new FormGroup({
      token: new FormControl(),
      handle: new FormControl(this.captchaData.handle),
    });
}

submit() {
    this.captchaService.postCaptcha(this.captchaForm.value)
      .subscribe( (response: any) => {
      this.captchaData = response;
    });
  }
public getCaptcha() {
    this.captchaService.getCaptcha().subscribe(response => {
      this.captchaData = response;
      this.dataDisplay = true;
      console.log(response);
    });
  }

model.ts

export class Captcha {
  handle: string;
  imgCaptcha: string;
  token: string;
}

captcha.service.ts

postCaptcha(token: Captcha) {
    return this.http.post(environment.ApiUrl + `/api/url`, token, {responseType: 'text'});
  }

getCaptcha() {
    return this.http.get<any>(environment.ApiUrl + `/api/urlCaptcha`);
  }

Do you know how resolve this? Thanks


Solution

  • Your FormGroup isn't initialised by the time you are using it. So remove it from ngOnInit

    captchaData: Captcha;
    captchaForm: FormGroup = new FormGroup({
      token: new FormControl(),
      handle: new FormControl()
    });
    

    use patchValue to update your form value:

    public getCaptcha() {
      this.captchaService.getCaptcha().subscribe(response => {
      this.captchaData = response;
      this.dataDisplay = true;
      console.log(response);
      this.captchaForm.patchValue({
         handle: this.captchaData.handle
        });
     });
    }