首页 > 解决方案 > Angular 表单控件不只更新 UI 的值

问题描述

我有这样的表格:

this.filterFormGroup= this.formBuilder.group({
      gmt_scope: [''],
      priority: [''],
      region: [''],
      category: [''],
      status: [''],
      original_deadline: [''],
      responsibles: [''],
      pms: [''],
      updated_at: ['']
    });

表单通过 API 填充:

<form [formGroup]="filterFormGroup" >
          <div fxLayout="row" fxLayoutWrap="wrap" fxLayout="center center"  class="row">
            <div fxFlex.gt-sm="20" fxFlex="100" class="p-10" fxLayoutAlign="center center">
              <!-- <mat-slide-toggle color="primary" stepper="0" formControlName="gmt_scope">GMT SCOPE</mat-slide-toggle> -->
              <mat-form-field>
                <mat-select  placeholder="GMT Scope" stepper="0" formControlName="gmt_scope" >
                  <mat-option *ngFor="let gmt_scope of gmt_scopes" [value]="gmt_scope.value" >
                    {{ gmt_scope.viewValue }}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>
            <div fxFlex.gt-sm="20" fxFlex="100" class="p-10" fxLayoutAlign="start center">
              <mat-form-field>
                <mat-select placeholder="Priority" stepper="0" formControlName="priority">
                  <mat-option *ngFor="let priority of projectAttributes.priorities" [value]="priority.id" >
                    {{ priority.description }}
                  </mat-option>
                </mat-select>
              </mat-form-field>
            </div>

准备好后,我阅读了一些 queryParams 并设置了一些表单字段,如下所示:

setFiltersFromParams(params){
    if ('pms' in params){
      this.filterFormGroup.controls.pms.setValue(params.pms.split(","));
      console.log("Setting the following pms:",params.pms.split(",") )
    }
    if ('region' in params){
      this.filterFormGroup.controls['region'].setValue(params.region,{emitEvent: true});
      console.log("Setting the following region:",params.region )
    }

  }

如果我检查控件值,它们会正确更新,但从 UI 中我看不到选择的选项,它们未被选中。

标签: angularangular5angular-forms

解决方案


正如您所说,您的 GUI 未更新值,但变量中的控制值已更新此问题与更改检测有关。

ChangeDetectorRef做一件事在组件级别注入服务,即

在组件的构造函数中定义private ChangeDetectorRef cd

以及在自定义事件函数中以编程方式更新控件的位置调用此函数,如下所示cd.detectChanges()

按照这个链接它会有所帮助。


推荐阅读