Search code examples
angulardropdownangular-ng-if

Show and Hide container of dropdownList Angular 9


I have three dropdown lists and three components to render the results. This works ok, but once one is selected, the other still remains. I've searched for answers, and is ngIf the best answer? If so how do I implement these boolean flags?

html

<div class="container-fluid">
  <div class="row">

    <div class="col-md-6 offset-md-3">

      <mat-form-field style="width:100%;">
        <mat-label>Choose a Category</mat-label>
        <mat-select [(value)]="category" (selectionChange)="searchByCategory() ">
          <mat-option *ngFor="let n of nobelCategory" [value]="n.name">
            {{n.name}}
          </mat-option>

        </mat-select>


      </mat-form-field>
    </div>
    <div class="col-md-6 offset-md-3">
      <mat-form-field style="width:100%;">
        <mat-label>Choose a Country</mat-label>
        <mat-select [(value)]="country" (selectionChange)="searchByCountry() ">
          <mat-option *ngFor="let c of countries" [value]="c.name">
            {{c.name}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>

    <div class="col-md-6 offset-md-3">
      <mat-form-field style="width:100%;">
        <mat-label>Choose a year</mat-label>
        <mat-select [(value)]="year" (selectionChange)="searchByYear() ">
          <mat-option *ngFor="let year of numbers" [value]="year">
            {{year}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>



    <!-- CARDS RESULT-->

    <app-card-winners  [nobelWinner]="nobelWinner"></app-card-winners>
    <app-selection [countryWinner]="countryWinner"></app-selection>
    <app-winners-by-year [years]="years"> </app-winners-by-year>

    <!-- CARDS RESULT END-->

  </div>
</div>

TS:

       searchByCategory() {
                   console.log(this.category)
                    this.dataService.searchByCategory(this.category)

                    .subscribe(data => {
                     this.nobelWinner = data
                       console.log(data)
        this.isType='nobel';

      })
  }

Thw error I get is: Bindings cannot contaiagn assifments at column 8 [isType='nobel


Solution

  • Yes you can use ngIf for this situation

    <app-card-winners *ngIf="isType== 'nobel'"  [nobelWinner]="nobelWinner"></app-card-winners>
    <app-selection *ngIf="isType== 'winner'"  [countryWinner]="countryWinner"></app-selection>
    <app-winners-by-year *ngIf="isType== 'years'" [years]="years"> </app-winners-by-year>
    

    in component create variable like isType="";

    then change it inside change event functions searchByCountry(),searchByYear() ,searchByCategory().

    As example,

    searchByCategory(){
       //your conditions...
       this.isType='nobel';
    }