Search code examples
javascripthtmlangulartypescriptangular-ng-if

How to show or hide the data based on dropdown selection


In my angular application I have a dropdown list and below that some data is in div.

component.html

<select class="form-control" id="power" required>
  <option value="" disabled selected>Select a category</option>
  <option *ngFor="let category of categoryNames">{{ category }}</option>
</select>

<!--below code I have to show or hide-->

<div class="row">
  <div class="col-sm-8">
    <p>Slect Habits</p>
    <h5 class="formxp">Slect Items</h5>
  </div>
  <div class="col-sm-4">
    <p>Slect Habits</p>
    <h5 class="formxp">Slect Items</h5>
  </div>
</div>

So my requirement is when I click on any of the items from the dropdown list I have to show the div (after the dropdown in above code)

Can anyone help me regarding the same.


Solution

  • You can define a template variable (e.g. #mySelect) on the <select> element, then use it to determine the selected value: mySelect.value.

    In case you need to display the div if the selected category equals to 'Habit', you can try the following:

    <!-- #mySelect is declared on <select> element -->
    <select class="form-control" id="power" required #mySelect>
      <option value="" disabled selected>Select a category</option>
      <option *ngFor="let category of categoryNames">{{ category }}</option>
    </select>
    
    <div class="row" *ngIf="mySelect.value === 'Habits'">
      <div class="col-sm-8">
        <p>Slect Habits</p>
        <h5 class="formxp">Slect Items</h5>
      </div>
      <div class="col-sm-4">
        <p>Slect Habits</p>
        <h5 class="formxp">Slect Items</h5>
      </div>
    </div>
    

    You can read more about the Angular Template Variable here: https://angular.io/guide/template-reference-variables