I have an input item that upon updating to certain values raises an "are you sure?" type confirmation. If the user says yes, the logic continues, and if not, then the logic does not happen. However, the value still stays at what it was before and does not revert. How can I revert it?
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
}
}
If the ngModel were not bound to an async
, then I could just do [ngModel]="storeValue"
and then in the else
block do storeValue = this.initialValue
. Given that the value does come from an async value, is there a way for me to properly reset it?
So I found a solution, by using ViewChild
as follows:
<p-dropdown [options]="valueOptions" [ngModel]="storeValue$ | async"
(ngModelChange)="checkChange($event)" #storeValueDropDown name="storeValueDropDown"> </p-dropdown>
Then
@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
}
}