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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With