Osaf
Osaf

Reputation: 87

TypeError: Cannot read property 'formModel' of undefined

I'm getting this error when using reactive forms. Here is my code

<div [formGroup]="service.formModel" fxLayout="row" fxLayout.xs="column">
    <mat-form-field fxFlex="33%" appearance="outline">
      <mat-label class="label-text">District</mat-label>
      <mat-select formControlName="District">
        <mat-option value="None">None</mat-option>
        <mat-option *ngFor="let district of districts" [value]="district.value">{{district}}</mat-option>
      </mat-select>
      <mat-icon class="icon-color" matSuffix>layers</mat-icon>
    </mat-form-field></div>

and here is an array of Districs:

component file

districts:string[] = [
  'Queensland', 'New South Wales','Australian Capital Territory'];

services file!

  formModel = this.fb.group({
 District:['']});

Why i'm getting this error maybe because district is null or something?

Upvotes: 1

Views: 331

Answers (2)

Wandrille
Wandrille

Reputation: 6811

you are using Service which is null directly in the HTML.

If it is indeed a service (correctly defined in your constructor), then define formModel in your ngOnInit for example in your component:

formModel: FormGroup;

ngOnInit(): void {
   this.formModel = this.service.getFormModel();
}

and in your HTML:

<div [formGroup]="formModel" fxLayout="row" fxLayout.xs="column">

And in your service:

getFormModel(): FormGroup {
  return this.fb.group({
    District:['']
  });
}

Upvotes: 3

Pardeep Jain
Pardeep Jain

Reputation: 86740

You have syntax error, code should be like this -

<div [formGroup]="formModel" fxLayout="row" fxLayout.xs="column">
.....
  • FormGroup should be formGroup
  • Binding with formgroup should be formModel instead of Service.formModel

Upvotes: 1

Related Questions