Home > Net >  Hide input field on certain conditions
Hide input field on certain conditions

Time:11-30

I have an input field and I want it hidden, it should only be visible if the selection from the dropdown menu is "Type of Aircraft": Here is the html code:

<mat-form-field appearance="outline" class="width-1 col-4">
      <mat-label>Type</mat-label>
      <mat-select formControlName="typeId">
        <mat-option *ngFor="let type of typeList" [value]="type.id">
          {{ type.name }}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <mat-form-field appearance="outline" class="width-1 col-4">
      <mat-label>Type of Motor</mat-label>
      <input
        matInput
        placeholder="Type of Motor"
        formControlName="typeMotor"
        name="typeMotor"
        id="typeMotor"
      />
    </mat-form-field>

The first mat-form-field is the dropdown menu, and the second mat-form-field is the field that I want to be hidden or visible on certain conditions.

Here is the sample photo

CodePudding user response:

Create a variable in TS file called typeId and pass in mat-select [(ngModel)]="typeId" like this. then add ngIF condition on input like this *ngIf="typeId == 4"

CodePudding user response:

I would take an observable approach and attach an observable to [hidden]. You can listen to valueChanges of your form control and act accordingly. Remeber that even if you hide your form control, it is still present in your form, maybe you would want to also disable it, then it will not even appear in the formvalue, unless you call getRawValue(). So I would suggest the following:

isHidden$: Observable<boolean>;

// build your form, then call
this.isHidden$ = this.myForm.get('typeId').valueChanges.pipe(
  map((value: number) => {
    return this.typeList.find((x) => x.id === value)?.name !==
      'Type of Aircraft';
  })
);

Then attach this to your input:

  <input
    matInput
    [hidden]="isHidden$ | async"
    placeholder="Type of Motor"
    formControlName="typeMotor"
    name="typeMotor"
    id="typeMotor"
  />
  • Related