【问题标题】:Reset an ngModel async value if not confirmed如果未确认,请重置 ngModel 异步值
【发布时间】:2020-12-28 09:28:49
【问题描述】:

我有一个输入项,在更新到某些值时会引发“您确定吗?”类型确认。如果用户说是,则逻辑继续,如果不是,则逻辑不发生。但是,该值仍保持在以前的水平,并且不会恢复。我怎样才能恢复它?

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。鉴于值确实来自异步值,我有办法正确重置它吗?

【问题讨论】:

    标签: angular asynchronous angular-ngmodel


    【解决方案1】:

    所以我找到了一个解决方案,使用 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 2016-11-25
      • 2021-12-09
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2012-07-19
      • 2010-12-12
      相关资源
      最近更新 更多