简体   繁体   中英

How to use Reactive FormGroup with Angular Material

I'm using reactive form group with Angular Material design. However, I'm getting an error:

ERROR TypeError: Cannot read property 'invalid' of undefined

Pointing to this line of code:

<input formControlName="fieldName" ngDefaultControl matInput placeholder="Field Name">
<mat-error *ngIf="fieldName.invalid">
  Field name is required
</mat-error>

TS:

export class AddFieldComponent implements OnInit {
  form: FormGroup;

  constructor(public fb: FormBuilder) {
      this.form = this.fb.group({
        fieldName: ['', Validators.required],
        fieldType: ['', Validators.required]
      });
    }
  }

HTML

<div [formGroup]="form" class="add-field">
  <div mat-dialog-content>
    <h2>Add Fields</h2>
    <mat-form-field>
      <input formControlName="fieldName" ngDefaultControl matInput placeholder="Field Name">
      <mat-error *ngIf="fieldName.invalid">
        Field name is required
      </mat-error>
    </mat-form-field>
    <mat-form-field>
      <mat-select formControlName="fieldType">
        <mat-option value="text-field">Text Field</mat-option>
        <mat-option value="radio-btn">Radio Button</mat-option>
      </mat-select>
    </mat-form-field>
  </div>
  <div mat-dialog-actions>
    <span class="right-align-next-element"></span>
    <button class="secondary-btn" mat-button (click)="closeModal()">Cancel</button>
    <button [disabled]="fieldName.invalid" class="primary-btn" mat-button (click)="addFields()" cdkFocusInitial>Add field</button>
  </div>
</div>

There are two options you have.

Option 1

Wrap the element with a div or span with below check

*ngIf="fieldName && fieldName.invalid"

Option 2

Always use:

fieldName?.invalid

When you want to access invalid property of fieldName

Since you don't have a variable in typescript where you store FormControl object (example fieldName: FormControl), you cannot use *ngIf="fieldName.invalid" in html template, just because fieldName is not a variable.

I solved by getting controls from form variable (form: FormGroup) *ngIf="form.get('fieldName')?.invalid" . Also in the buttons in bottom [disabled]="!form.dirty || form?.invalid" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM