Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect changes in a list of drop down elements?

Tags:

angular

I have a list of users. Each user is a composite object: { id: '123', name: 'Bob', State: 'Colorado' }

I render those users using an *ngFor:

<div *ngFor="let u in users">
    {{ u.name }}
    <select [(ngModel)]="u.state">
       <option *ngFor="let s in states" [value]="s">{{s}}</option>
    </select>
</div>

When select-value changes - I want to save the object over REST API.

I tried adding (change)="changeState(u)", but that does not work, apparently u.state is being updated after my (change) callback is executed.

If I would not have a loop, I would give my dropdown a reference: #state and then use (change)="changeState(u, state.value)"

Is my only option is to use $event.target.value? Or is there a slicker way to do this? This solution also takes away validation.

Is any of the first two solution attempts salvageable?

like image 444
THX-1138 Avatar asked Nov 25 '25 09:11

THX-1138


2 Answers

You can separate the ngModelChange event from ngModel:

<select [ngModel]="u.state" (ngModelChange)="changeState($event)">
       <option *ngFor="let s in states" [value]="s">{{s}}</option>
</select>

then the new select value will be passed to changeState() directly.

like image 190
Daniel Kucal Avatar answered Nov 28 '25 00:11

Daniel Kucal


If you're using then you can go with

HTML

<div *ngFor="let u in users">
    {{ u.name }}
    <select formControlName="dropdown" (change)="modelChange($event)">
       <option *ngFor="let s in states" [value]="s">{{s}}</option>
    </select>
</div>

TS

modelChange(event){
console.log(event.target.value);
}
like image 31
Abhishek Ekaanth Avatar answered Nov 28 '25 01:11

Abhishek Ekaanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!