【问题标题】:the button does not coming back into original state when subcribe completed订阅完成后按钮不会恢复到原始状态
【发布时间】:2021-12-15 02:52:47
【问题描述】:

我从父级传递一个对象数组,其中包含一个按钮,在这个按钮中我有 2 个属性,启用和禁用按钮,还有一个执行功能,按钮工作正常,当我单击按钮时变为disabled,在请求执行时,但一旦完成,就不会再次启用,尽管 this.loading 属性再次为 false。

// parent-component.ts
private initForm() {
    this.jsonForm = {
      controls: [
        {
          /// code
        },
        {
          type: 'button',
          label: 'Send',
          disabled: () => this.handleLoading(),
          action: (formValue) => this.onSubmit(formValue)
        }
      ]
    }
  }

  handleLoading(): boolean {
    return this.loading
  }


  onSubmit(formValue) {
    this.loading = true
    this.auth.login(formValue)
      .subscribe(
        () => {
          this.loading = false
        },
        err => {
          this.loading = false
          console.log('eror', err)
        }
      )
  }
// parent-component.html
<DynamicForm [jsonForm]="jsonForm"></DynamicForm> 
// child-component.html
 <ng-container *ngFor="let control of jsonForm?.controls">
            <ng-container *ngIf="control.type==='button'">
                <UIButton 
                    (click)="control.action(myForm.value)"
                    [disabled]="control.disabled()">
                        <span *ngIf="!control.disabled()">{{control.label}} <i *ngIf="icon" class="{{icon}} mr-1"></i></span>
                        <span class="blink" *ngIf="control.disabled()">Wait <i class="fa fa-spinner fa-spin"></i></span>
                </UIButton>
            </ng-container>
</ng-container>

【问题讨论】:

  • 尝试禁用:this.handleLoading 而不是禁用:() => this.handleLoading(),
  • 请把你的代码上传到stackblitz,对你有帮助很容易

标签: angular components angular-promise


【解决方案1】:

因为 Angular 实际上无法检测原始值的变化。

例如开头的 this.loading 是 true,所以 angular 会引用 "true" 并检查 true 是否发生变化。 True 始终保持为 true,因为您将其替换为完全不同的值“false”。 Angular 无法检测到这一点。整数也是如此,它无法检测到 1 已更改为 0,因为它会将其检查为 对象引用 而不是值

您需要创建一个名为:

public loading$: BehaviorSubject = new BehaviorSubject(false);

然后在disabled属性中切换(去掉handleLoading):

disabled: this.loading$,

当你想切换你使用的值时:

this.loading$.next(true);
this.loading$.next(false);

UI Button 应该使用异步管道

  <UIButton [disabled]="control.disabled | async">
                       

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 2019-12-24
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    相关资源
    最近更新 更多