Home > OS >  How to hide a HTML element using an if-statement?
How to hide a HTML element using an if-statement?

Time:04-26

My application allows the user to upload files to a database, I also have a mat-select component where the user is able to select which excel worksheet they would like to upload.

I would like to hide this mat-select component IF the user selects a CSV file, however my [hidden]="hideDropdown" doesn't seem to work.

hideDropdown: boolean;

if (this.file.type == "text/csv") {
  this.hideDropdown = true;
} else {
  this.hideDropdown = false;
}
<mat-form-field *ngIf="sourceFile" id="worksheetStyle" appearance="fill">
  <mat-label>Excel Worksheet</mat-label>
  <mat-select [hidden]="hideDropdown" [(ngModel)]="selectedSheet" (selectionChange)="selectWorksheet()">
    <mat-option *ngFor="let worksheet of worksheetNames" [value]="worksheet">
      {{worksheet}}
    </mat-option>
  </mat-select>
</mat-form-field>

CodePudding user response:

I believe that the reason [hidden] attribute isnt working is because it doesnt exist on mat-select only on html-tags as it is a core html attribute. What you could do instead is use *ngIf as follows:

  <mat-select *ngIf="hideDropDown" [(ngModel)]="selectedSheet" 
  (selectionChange)="selectWorksheet()">
   <mat-option *ngFor="let worksheet of worksheetNames" [value]="worksheet">
     {{worksheet}}
   </mat-option>
 </mat-select>

However it should be noted that the *ngIf will remove the select from the DOM entirely whilst [hidden] is just applying a display: none to the element thus having it still be rendered in the DOM. So if you've created a reactive form that expects to have a select input it will cause error if you remove it with ngIf. However it seems that you are just using the select by itself and with a ngModel so that shouldnt be an issue for you.

Edit 1:

Working stackblitz showing a possible solution: https://stackblitz.com/edit/angular-5ykmue?file=src/app/select-overview-example.html

Edit 2:

I stand corrected with not being able to use the [hidden] attribute, if you wrap the form-field in a div you can then use hidden to show / hide as follows:

<div [hidden]="hideDropdown">
<mat-form-field *ngIf="sourceFile" id="worksheetStyle" appearance="fill">
  <mat-label>Excel Worksheet</mat-label>
  <mat-select [(ngModel)]="selectedSheet" (selectionChange)="selectWorksheet()">
    <mat-option *ngFor="let worksheet of worksheetNames" [value]="worksheet">
      {{worksheet}}
    </mat-option>
  </mat-select>
</mat-form-field>
</div>
  • Related