Search code examples
angularformsselectangular6dropdown

Angular 6 - Select inside an ngFor


I have a select dropdown inside a ngFor. How do I retrieve the value of each select inside the loop?

Also, I want to change the color of each sentence inside the <p> tag depending on each select's value. How would I do that?

image

Each sentence should have a color depending on the value selected in the dropdown next to it. And the change needs to be immediate.

The code here does not work.

<div *ngIf="sentences?.length > 0;else noItems">
  <ul *ngFor="let sentence of sentences;let i = index;" class="collection">
  <li class="collection-item">
     <p>{{sentence.data}} </p>
     <p style="margin-left:20px; font-size:12px!important"> 
        <select  (change)="filterChanged(selected[i])">
        <option *ngFor="let cat of foods" [value]="cat.value">
        {{cat.viewValue}}
        </option>
        </select>
     </p>
  </li>

ts file:

filterChanged(selectedValue:string ){
    this.printedOption = selectedValue;
    console.log("COLOR",this.printedOption );
    if(this.printedOption=='1'){
        this.color="pink";
    }
    if(this.printedOption=='2'){
        this.color="red";
    }
}

Solution

  • You can use [ngClass] with the multiple conditions to apply a CSS class

    HTML Code:

    <div>
        <ul *ngFor="let sentence of sentences;let i = index;" class="collection">
            <li class="collection-item">
                <p [ngClass]="{'red': sentence?.disco == 1 , 'green': sentence?.disco == 2 }">{{sentence.viewValue}} </p>
                <p style="margin-left:20px; font-size:12px!important">
                    <select #val (change)="onChange(val.value,i)">
                <option *ngFor="let cat of foods" [value]="cat.value" >
                {{cat.viewValue}}
                </option>
                </select>
             </p>
          </li>
       </ul>
    </div>
    

    CSS:

    .red{
      background-color: red;
    }
    
    .green{
      background-color: green;
    }
    

    TS Code:

    import { Component } from '@angular/core';
    
    /**
     * @title Basic select
     */
    @Component({
      selector: 'select-overview-example',
      templateUrl: 'select-overview-example.html',
      styleUrls: ['select-overview-example.css'],
    })
    export class SelectOverviewExample {
      foods: any[] = [
        { value: '1', viewValue: 'Pizza' },
        { value: '2', viewValue: 'Tacos' }
      ];
    
      sentences: any[] = [
        { value: 'steak-0', viewValue: 'Steak' },
        { value: 'pizza-1', viewValue: 'Pizza' },
        { value: 'tacos-2', viewValue: 'Tacos' }
      ];
    
      onChange(selectedValue, index) {
        console.log(selectedValue)
        this.sentences[index].disco = selectedValue;
      }
    }
    

    Stackblitz Demo