Search code examples
angularangular7html-listsangular-ng-if

How to display one list or another in the same angular component through buttons?


I have two lists in my html

<div class="list" *ngIf="models !== undefined && models.length">
    <div class="model" *ngFor="let model of menuModels">
        <div class="name">{{model.name}}</div>
    </div>
    <div class="operator" *ngFor="let operator of menuOperators">
        <div class="name">{{operator.name}}</div>
    </div>
</div>

and I have created two buttons in the same menu to show one or the other, depending on the button selected

    <div class="buttons">
        <div class="btn" (click)="showModels()"><p class="initial">M</p></div>
        <div class="btn" (click)="showOperators()"><p class="initial">O</p></div>
    </div>

Right now both lists are displayed in the same component. How can I manage an *ngIf through the buttons so that one or the other is shown according to the corresponding button? Or what would be the best way to do it? Thank you in advance


Solution

  • In your component take a boolean instance variable that will act as a toggle for displaying your lists

    • Now when you click on showModels button make it true, that means you will display menuModels
    • Now when you click on showOperators button make it false, that means you will display menuOperators

    Try to use Boolean as more as you can rather comparing string. As. boolean will always have 1bit to store.

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'xyz-abc',
      templateUrl: './xyz-abc.html',
      styleUrls: ['./xyz-abc.css']
    })
    export class XYZComponent implements OnInit {
      isDisplayModel: boolean = true;
      constructor(
    
      ) {
    
      }
    
      ngOnInit() {
      }
    
      showModels(){
        isDisplayModal = true;
      }
      showOperators(){
        isDisplayModal = false;
      }
    }
    

    Your HTML code will look like below

    <div class="list" *ngIf="models !== undefined && models.length">
    <div class="row" *ngIf="isDisplayModal">
        <div class="model" *ngFor="let model of menuModels">
           <div class="name">{{model.name}}</div>
        </div>
    </div>
    
    <div class="row" *ngIf="!isDisplayModal">
        <div class="operator" *ngFor="let operator of menuOperators">
            <div class="name">{{operator.name}}</div>
        </div>
    </div>