【问题标题】:Angular 7 can't set value for mat-select form control [duplicate]Angular 7无法为mat-select表单控件设置值[重复]
【发布时间】:2019-12-11 03:54:08
【问题描述】:

我有这个带有几个表单控件的表单组:

myForm: FormGroup = new FormGroup({
    ...
    myControl: new FormControl(),
    ...
  });

表单控件myControl是这样的:

<mat-form-field class="col-large">
            <mat-select formControlName="myControl">
              <mat-option *ngFor="let data of dataMap" [value]="data.value">
                {{data.description}}
              </mat-option>
            </mat-select>
          </mat-form-field>

dataMap 基本上是一个具有属性值和属性描述的对象数组,它们都是字符串,所以对象的示例是:

{
  "value":"1",
  "description":"desc"
}

然后我有一个自动完成输入,它适用于同一个dataMap,并且每当用户开始输入时,它都会搜索数组的描述,只提示与所写文本匹配的那些。然后,当用户选择一个选项时,它调用一个从数组中检索对应值的方法,并将检索到的值设置为myControl。 The expected behaviour is that, when an option in the autocomplete is selected, the value is changed in myControl and a new description is shown.
问题是myControl 的值设置正确,但没有显示选定的选项。
我不明白的是,在 ngOnInit 方法中,我以这种方式从地图中为 myControl 设置了一个默认值:

this.myForm.get('myControl').setValue("1");

它正确选择了选项并将其显示为已选择。然后,在自动完成选择的回调方法中,我做同样的事情,但它没有被选中。表单控件变为空白。
我检查了从自动完成中获得的值,它存在于dataMap 中。在设置新值后,我还打印了 myControl 的值,它是正确的新值。

【问题讨论】:

  • 看不到代码就无法调试代码。
  • 我知道,但我不能发布代码和数据......我会尝试调整它,但我不知道我是否能做到

标签: angular angular7 formgroups


【解决方案1】:

改为这样做

let test = {
  "value":"1",
  "description":"desc"
}

this.myForm.get('myControl').setValue(test);

您应该将相同类型的对象传递给 myControl

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-11-16
    • 2020-12-05
    相关资源
    最近更新 更多