简体   繁体   中英

How to set drop-down value in Angular

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.

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");
} }

在此处输入图片说明

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM