gpt4 book ai didi

Angular 2选择(更改)事件,不更新下拉列表中的值

转载 作者:太空狗 更新时间:2023-10-29 19:29:51 25 4
gpt4 key购买 nike

When the select dropdown changes, I call a method with the (change) directive to check if the value selected is allowed, if the selected value is not allowed, I select the previous value again (还原下拉列表中的更改),但下拉列表中的选定值仍显示新的选定值,但 ngModel 变量是先前的值,例如:

我将选择从 A 更改为 B。

HTML:

<select (change)="doCheck()" [(ngModel)]="test">
<option [ngValue]="1">A</option>
<option [ngValue]="2">B</option>
</select>

组件:

test: number = 1;

doCheck(){
//Not allowed to change to B, so change back to A
this.test = 1;
}

test 变量值为 1,但 B 在下拉列表中仍处于选中状态。

然而,当我在 this.test = 1 上添加一个 setTimeout 时,值会变回 A,但我不想添加 setTimeout 在我的代码中无处不在。

任何帮助将不胜感激

最佳答案

改用ngModelChange

<select (ngModelChange)="doCheck()" [(ngModel)]="test">

确保 doCheck()ngModel 更新 test 后被调用

Angular 不保证事件绑定(bind)以任何特定顺序处理。但是 ngModelChange 是由 NgModel 在更新模型后发出的。

如果您修改 ngModel 更新的值,您可能需要

constructor(private cdRef:ChangeDetectorRef) {}

doCheck(){
//Not allowed to change to B, so change back to A
this.test = 1;
this.cdRef.detectChanges();
}

否则 ngModel 可能会保留旧值。

关于Angular 2选择(更改)事件,不更新下拉列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com