Reputation: 159
I have a drop-down menu where I would like to set a value using some logic in my TS file. This is what my drop-down looks like:
<select [(ngModel)]="selectedEntity" (change)="onChange();">
<option *ngFor="let item of Entities" [ngValue]="item.EntityID">{{item.EntityName}}</option>
</select>
On change, I would like to check for a condition, and then set a value based on that condition. However, I'm stuck because I can't seem to get the drop-downs value to update in the view. I've tried to set the selectedEntity
to a new value, but no success. How would I be able to set the selected value using the TS file?
Edit: For more clarity, I'm basically trying to confirm whether the selected choice is allowed for the current item in the Entities array. If it is allowed, select the option the user picked, if not, reset it to the previous value.
Upvotes: 0
Views: 2787
Reputation: 109
event handler registered in ngModelChange will be fired before the value of model changes. You have to pass event with change's event handler. You can try
(change)="onChange($event);"
Code
<select [(ngModel)]="selectedEntity" (change)="onChange($event);">
<option *ngFor="let food of foods" [ngValue]="food.name">{{food.name}}</option>
</select>
TS File
onChange(event:any){
console.log(this.selectedEntity)
}
Upvotes: 1
Reputation: 225
Try this out my friend, ngModelChange is the way to go. You can hook to the event.value to get access to your values
<select [(ngModel)]="selectedEntity" (ngModelChange)="onChange($event)">
<option *ngFor="let item of Entities" [ngValue]="item.EntityID">{{item.EntityName}}</option>
I made some changes to the stackblistz. On event you can hook to the value and use it
onChange(event) { if (event.id==1){
console.log("Value 1");
}
else if(event.id==2){
console.log("Value 2");
}
else if(event.id==3){
console.log("Value 3");
}else{
console.log("Update to Value 1");
} }
Upvotes: 2