首页 > 解决方案 > Angular: If this option in dropdown show this div

问题描述

How do you show and hide divs in Angular (4 thru 9) upon a user selecting an option(s) in a dropdown select?

My code below is only showing one/the same div no matter the option I select.

 public Terminated = true; 
 public Release = true;

selectedFilter:string;
   public filterTypes = [
   {value:'empty', display:''},  
   {value:'release', display:'Release Report'},
   {value:'reports', display:'Detail Report'},
   {value:'terminated', display:'Terminated Report'},
  ];

  constructor() { 
    this.selectedFilter='release';
  } 

  filterChanged(selectedValue:string){
    if(this.selectedFilter) {
       this.Terminated = false;
    } else {
    this.Release = false
   }
<select class="form-control" (change)="filterChanged($event.target.value)">
                  <option *ngFor="let type of filterTypes" [value]="type.value">{{type.display}}
                  </option>
                 </select>
                 
<div [hidden]="Terminated"><p>terminated content here</p></div>
<div [hidden]="Release"><p>release content here</p></div>

标签: angular

解决方案


In your code, you are checking selectedFilter to set the variables to true and false, but the value of this variable is only set in the constructor. Due to which the change in the select drop down is not having any affect.

You may change your code to the below,

component.html

<select class="form-control" [(ngModel)]="selectedFilter">
  <option *ngFor="let type of filterTypes" [value]="type.value">
    {{type.display}}
  </option>
</select>
                 
<div [hidden]="selectedFilter !== 'terminated'"><p>terminated content here</p></div>
<div [hidden]="selectedFilter !== 'release'"><p>release content here</p></div>
<div [hidden]="selectedFilter !== 'reports'"><p>detailed report content here</p></div>

component.ts

 selectedFilter:string;
 public filterTypes = [
   {value:'empty', display:''},  
   {value:'release', display:'Release Report'},
   {value:'reports', display:'Detail Report'},
   {value:'terminated', display:'Terminated Report'},
  ];

  constructor() { 
    this.selectedFilter = 'release';
  }

推荐阅读