Home > OS >  How show a disabled div based on dropdown selection Angular Material
How show a disabled div based on dropdown selection Angular Material

Time:12-16

i would like to show filters after their selection in a dropdown. At the moment i have some static disabled div and a dropdown where i can select them.

the dropdown:

<mat-form-field>
  <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
  <mat-select>
    <mat-option *ngFor="let filter of filters">
      {{filter.showValue | translate}}
    </mat-option>
  </mat-select>
</mat-form-field>

One of the filters:

<div  *ngIf="selected">
  <mat-form-field>
    <mat-label>{{ 'supplier.supplierName' | translate }}</mat-label>
    <input formControlName="companyName" matInput/>
  </mat-form-field>
</div>

CodePudding user response:

The faster way:

<mat-form-field>
  <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
  <mat-select (selectionChange)="selected = event.value">
    <mat-option *ngFor="let filter of filters">
      {{filter.showValue | translate}}
    </mat-option>
  </mat-select>
</mat-form-field>

Elegant way:

If you need selection in the form too, use a control for that:

filterForm: FormGroup = new FormGroup({
  selected: new FormControl(null, [Validators.required]),
  companyName: new FormControl('')
})

get selected(){
  return this.filterForm.controls.selected
}
<form [formGroup]="filterForm">
  <mat-form-field>
    <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
    <mat-select formControlName="selected">
      <mat-option *ngFor="let filter of filters">
        {{filter.showValue | translate}}
      </mat-option>
    </mat-select>
  </mat-form-field>

  <div  *ngIf="selected">
    <mat-form-field>
      <mat-label>{{ 'supplier.supplierName' | translate }}</mat-label>
      <input formControlName="companyName" matInput/>
    </mat-form-field>
  </div>
</form>
  • Related