简体   繁体   English

如何在 Angular 中设置下拉值

[英]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.我有一个下拉菜单,我想在其中使用 TS 文件中的某些逻辑设置一个值。 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.我试图将selectedEntity设置为一个新值,但没有成功。 How would I be able to set the selected value using the TS file?我如何能够使用 TS 文件设置选定的值?

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.试试这个,我的朋友,ngModelChange 是要走的路。 You can hook to the event.value to get access to your values您可以挂钩 event.value 以访问您的值

 <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.我对 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 .在 ngModelChange 中注册的事件处理程序将在模型更改值之前被触发 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 TS文件

    onChange(event:any){
        console.log(this.selectedEntity)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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