首页 > 解决方案 > 打开带有单选按钮组的 Angular 模态窗口会导致 ExpressionChangedAfterItHasBeenCheckedError

问题描述

我是 Angular 的新手,并试图遵循生命周期钩子,但显然,我并不完全理解它们。

在我的项目中,我有一个包含在模式窗口中的单选按钮组。模态是通过在用户请求下单击按钮打开的,所以没有什么是自动的。显示窗口时需要默认选择每月选项。

打开模态窗口时,我的开发工具控制台中出现以下错误:

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'焦点:未定义'。当前值:'焦点:真'。

我尝试过的事情:

在这一点上,我很困惑,希望得到一些指导。

带有单选按钮组的模态的 HTML:

  <ng-template #subscriptionOptions let-modal>
    <form #subForm='ngForm'>
    <div class="modal-body" id="subInfo">
      <section class="widget">

          <h4>
            <fa-icon [icon]="['far','check-square']"></fa-icon>
            {{ currentUser.firstName }}, please choose and activate your subscription
          </h4>

        <div name="subType" id="subType" class="btn-group btn-group-toggle" ngbRadioGroup [(ngModel)]="subType" style="margin-left: 117px">
          <label class="BG-Def" ngbButtonLabel>
            <input name="monthly" id="monthly" type="radio" [value]="'monthly'" ngbButton  (click)="subType = 'monthly'">
            Pay Monthly
          </label>
          <label class="BG-Def" ngbButtonLabel>
            <input name="annual" id="annual" type="radio" [value]="'annual'" ngbButton  (click)="subType = 'annual'">
            Pay Annualy (Save 20%)
          </label>
        </div>


              <div class="row">
                <div class="col-md-8 col-md-offset-3">
                  <button type="submit" class="btn btn-danger">Activate Subscription</button>
                  <button type="button" class="btn btn-default" (click)="closeSubOptions()">Cancel</button>
                </div>
              </div>



      </section>
    </div>
    </form>
  </ng-template>

我在构造函数中设置 subType 值:

constructor(private modalDialogService: ModalDialogService) {
this.subType = 'monthly';
}

然后这是我打开模态本身的方式:

HTML 按钮:

(click)="this.openSubOptions(subscriptionOptions)"

打字稿:

  public openSubOptions(modal) {
      this.modalService.open(modal, {size: 'lg', windowClass: 'subModal'});
  }

ngOnInit 和 ngAfterViewInit

public ngOnInit() {
    this.passChange = false;
    this.navBar.updateUser.subscribe((result) => {
      this.currentUser = this.auth.getLoggedInUser();
    });
    this.currentUser = this.auth.getLoggedInUser();
    this.getSessionExpiration();
    this.timer = setInterval(() => {
      this.onTimeoutTick();
    }, 1000);
    this.dialogCallback.subscribe(() => this.resetTimer());
  }

  public ngAfterViewInit() {
    this.cd.detectChanges();
  } 

标签: angulartypescriptbootstrap-modal

解决方案


我最终找到了一项工作,围绕抽奖焦点远离我的广播组。

我在我的广播组之前添加了一个不可见的输入,这似乎可以防止发生更改错误。

<input type="text" style="display:none" />

推荐阅读