如果未确认,则重置 ngModel 异步值
Reset an ngModel async value if not confirmed
我有一个输入项,在更新到某些值时会引发“你确定吗?”类型确认。如果用户说是,则逻辑继续,如果不是,则逻辑不会发生。但是,该值仍然保持在之前的值并且不会恢复。我怎样才能恢复它?
HTML
<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
(ngModelChange)="checkChange($event)"> </p-dropdown>
TS
storeValue$.pipe(tap(value=>this.initialValue = value)); // initialValue is used to compare values in the confirm
checkChange(newValue){
if(confirm) //psudo-code for if user has accepted change
{
// do logic and update value
} else {
// do not update
// ideally set ngModel to this.initialValue
}
}
如果 ngModel 未绑定到 async
,那么我可以只执行 [ngModel]="storeValue"
,然后在 else
块中执行 storeValue = this.initialValue
。鉴于值 来自异步值,我有办法正确重置它吗?
所以我找到了一个解决方案,使用 ViewChild
如下:
<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
(ngModelChange)="checkChange($event)" #storeValueDropDown name="storeValueDropDown"> </p-dropdown>
然后
@ViewChild('storeValueDropDown') cld: Dropdown;
storeValue$.pipe(tap(value=>this.initialValue = this.valueOptions.find(o=>o.value===value))); // initialValue is now used to reset a rejected value
checkChange(newValue){
if(confirm) //psudo-code for if user has accepted change
{
// do logic and update value
} else {
// do not update
this.cld.selectedOption = this.initialValue ;
this.cld.focus(); // I do not know why this is needed -looks like a PrimeNg bug
}
}
我有一个输入项,在更新到某些值时会引发“你确定吗?”类型确认。如果用户说是,则逻辑继续,如果不是,则逻辑不会发生。但是,该值仍然保持在之前的值并且不会恢复。我怎样才能恢复它?
HTML
<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
(ngModelChange)="checkChange($event)"> </p-dropdown>
TS
storeValue$.pipe(tap(value=>this.initialValue = value)); // initialValue is used to compare values in the confirm
checkChange(newValue){
if(confirm) //psudo-code for if user has accepted change
{
// do logic and update value
} else {
// do not update
// ideally set ngModel to this.initialValue
}
}
如果 ngModel 未绑定到 async
,那么我可以只执行 [ngModel]="storeValue"
,然后在 else
块中执行 storeValue = this.initialValue
。鉴于值 来自异步值,我有办法正确重置它吗?
所以我找到了一个解决方案,使用 ViewChild
如下:
<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
(ngModelChange)="checkChange($event)" #storeValueDropDown name="storeValueDropDown"> </p-dropdown>
然后
@ViewChild('storeValueDropDown') cld: Dropdown;
storeValue$.pipe(tap(value=>this.initialValue = this.valueOptions.find(o=>o.value===value))); // initialValue is now used to reset a rejected value
checkChange(newValue){
if(confirm) //psudo-code for if user has accepted change
{
// do logic and update value
} else {
// do not update
this.cld.selectedOption = this.initialValue ;
this.cld.focus(); // I do not know why this is needed -looks like a PrimeNg bug
}
}