Soulzityr
Soulzityr

Reputation: 456

Angular Material: How to hide input field based on checkbox

I have a checkbox cbAddVestingOption that, when checked, should display an input field.

<mat-form-field style="width: 600px">
                  <mat-checkbox [formcontrolname]="cbAddVestingOption" style="padding-bottom: 200px;">Add Vesting Option</mat-checkbox>
                  <input type="text" placeholder="Vesting Option" matInput formcontrolname="vestedoption" [matAutocomplete]="auto" class="uppercase" />
                  <mat-autocomplete #auto="matAutocomplete">
                    <mat-option *ngFor="let option of vestedOptions" [value]="option">
                      {{option}}
                    </mat-option>
                  </mat-autocomplete>
                </mat-form-field>

So when cbAddVestingOption is checked, vestedoption should display. When cbAddVestingOption is not c hecked, vestedoption should be hidden.

Do I need to do this in the typescript or can I do it in the html?

Upvotes: 0

Views: 3357

Answers (1)

Trismuto
Trismuto

Reputation: 415

You can do it directly on the template like this:

  <mat-checkbox #checkbox>Add Vesting Option</mat-checkbox>
  <input type="text" placeholder="Vesting Option" matInput [hidden]="!checkbox.checked"/>

ADDED: A better option, using *ngIf on the whole <mat-form-field>:

<mat-checkbox #checkbox>Add Vesting Option</mat-checkbox>
<mat-form-field *ngIf="checkbox.checked" style="width: 600px">
    <input type="text" placeholder="Vesting Option" matInput formControlName="vestedoption" [matAutocomplete]="auto" />

Upvotes: 1

Related Questions