Search code examples
formsangular5angular6angular-reactive-formsform-control

angular6: How to toggle between hiding and showing a form control


I am unable to toggle between hiding and showing a control using a select embedded in an Angular6 reactive form. I want when the user select option3 in the garde form controll the name form controll is shown.

this.form = this.fb.group({
  id: [null, Validators.compose([Validators.required])],
  name: [null, Validators.compose([Validators.required])],
  grade: [null, Validators.compose([Validators.required])],

});

.html

<mat-form-field class="mb-1">
<input  matInput  " [formControl]="form.controls['id']">
</mat-form-field>


<mat-form-field class="mb-1">
<mat-select  [formControl]="form.controls['grade']">

<mat-option value="option1">option1</mat-option>
<mat-option value="option2">option2</mat-option>
<mat-option value="option3">option3</mat-option>
</mat-select>
</mat-form-field>

<mat-form-field class="mb-1">
<input  matInput  " [formControl]="form.controls['name']">
</mat-form-field>

Solution

  • Fastest solution would be, although not very elegant:

    <mat-form-field class="mb-1" *ngIf="form.controls['grade'].value == 'option3'">
      <input  matInput [formControl]="form.controls['name']">
    </mat-form-field>