角度表单控件不更新 UI 仅更新值

Ker*_*y82 7 angular angular-forms angular5

我有一个这样的表格:

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

表单通过 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>
Run Code Online (Sandbox Code Playgroud)

准备好后,我阅读了一些 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 )
    }

  }
Run Code Online (Sandbox Code Playgroud)

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

小智 7

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

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

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

以及您在自定义事件函数中以编程方式更新控件的地方调用此函数cd.detectChanges()

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