angular - 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 中我看不到选择的选项,它们未被选中。
解决方案
正如您所说,您的 GUI 未更新值,但变量中的控制值已更新此问题与更改检测有关。
ChangeDetectorRef
做一件事在组件级别注入服务,即
在组件的构造函数中定义private ChangeDetectorRef cd
。
以及在自定义事件函数中以编程方式更新控件的位置调用此函数,如下所示cd.detectChanges()
。
按照这个链接它会有所帮助。
推荐阅读
- python - 如果我在 for 语句中设置两个参数会发生什么?
- java - Avro 模式对象 - 递归
- c# - MS dotnet core 容器镜像拉取失败,错误:CTC1014
- c - 为什么switch语句在数字计数C程序中将整数计为空白字符?
- javascript - 反应原生导航:更改 headerRight flex
- azure-functions - 调用 context.done() 的最佳方式所需的建议
- java - 如何为具有私有访问说明符的内部类编写 Junit 测试用例?
- javascript - 使用 Blazor 加载 DOM 后关注输入字段
- android - android studio中的Pdf Viewer gradle问题
- questdb - 如何计算 QuestDB 上的移动平均线?