0
votes

I'm using ngFor gets label and select dropdown list in particular div tag in angular 7. But if i select option from any one select dropdown its changes happens in all select dropdown list in div tag

<div class="row">
    <ng-container *ngFor='let item of Bedroom.PBeda'>
        <div class="col-lg-3 col-md-6 col-sm-6 col-12">
            <span class="font-wt-600">{{item.PBedName}}</span><br /><br />
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6 col-12">
            <select class="form-control" name="value" id="bedID{{item.PBedID}}"[(ngModel)]="beds.value (ngModelChange)="onChangeBedsDetails($event,item.PBedID)">
                <option value="0">Select</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>
        </div>
    </ng-container>
</div>

enter image description here

1
can you make stackblitz example for this or share your onChangeBedsDetails methods code so we can better understand what you doing in that method. - Gurpreet Singh
pass type of bet to onchangeBedsDetails method and set value based on bed type - Gurpreet Singh

1 Answers

1
votes

The reason why all the drop down values are changing is because you have the same ngModel for all the dropdowns, instead store the values in an array as below:

Component HTML:

<div class="row">
    <ng-container *ngFor='let item of Bedroom.PBeda'>
        <div class="col-lg-3 col-md-6 col-sm-6 col-12">
            <span class="font-wt-600">{{item.PBedName}}</span><br /><br />
        </div>
        <div class="col-lg-3 col-md-6 col-sm-6 col-12">
            <select class="form-control" name="value" id="bedID{{item.PBedID}}" 
                    [(ngModel)]="beds.value[item.PBedID]" (ngModelChange)="onChangeBedsDetails($event,item.PBedID)">
                <option value="0">Select</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>
        </div>
    </ng-container>
</div>

Component TS:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  beds: any = {
    value: []
  }
  Bedroom: any = {
    PBeda: [
      {
        PBedID: 1,
        PBedName: 'hello'
      },
      {
        PBedID: 2,
        PBedName: 'hello2'
      }
    ]
  }

  onChangeBedsDetails(event, id) {
    console.log(this.beds.value[id]);
  }
}

Stackblitz Link