Condition input fields

December 8, 2020 · 3 min readLucian Ciobanu
Tags:Angular

Today I came across an interesting challenge at work: for two input fields and a button, how to make the second input field appear once the value is inserted in the first one and how to make the button appear only after both two input fields have values.

The first thing I had thought of was to use *ngIf for both the second input field and the button as such:

<div>
    <div>
      <span>Field 1</span>
      <mat-form-field appearance="outline">
        <mat-select name="field1" #firstField placeholder="Select">
          <mat-option *ngFor="let firstField of firstFieldValues" [value]="firstField">
            {{ firstField }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div *ngIf="firstField.value">
      <span>Field 2</span>
      <mat-form-field appearance="outline">
        <mat-select name="field2" #secondField placeholder="Select">
          <mat-option *ngFor="let secondField of secondFieldValue" [value]="secondField">
              {{ secondField }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div *ngIf="secondField.value">
      <button>
        {{ secondField.value }}
      </button>
    </div>
</div>

But in this situation, the evaluation of "secondField.value" will give an error because #secondField template variable doesnt exist until firstField.value exist.

After some head scratching, I realized I can do a better implementation with the [hidden] directive which hides the class but renders it and therefore asigns values to the secondField.

The change can be seen on line 12 where I'm using [hidden].

<div>
    <div>
      <span>Field 1</span>
      <mat-form-field appearance="outline">
        <mat-select name="field1" #firstField placeholder="Select">
          <mat-option *ngFor="let firstField of firstFieldValues" [value]="firstField">
            {{ firstField }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div [hidden]="!firstField.value">
      <span>Field 2</span>
      <mat-form-field appearance="outline">
        <mat-select name="field2" #secondField placeholder="Select">
          <mat-option *ngFor="let secondField of secondFieldValue" [value]="secondField">
              {{ secondField }}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div *ngIf="secondField.value">
      <button>
        {{ secondField.value }}
      </button>
    </div>
</div>

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery