无法在反应式中选择的设定值

时间:2019-08-28 06:14:01

标签: angular angular-reactive-forms

我的组件中有一个反应形式。初始化组件时,我想将值设置为组件中的select字段,而不是作为选项。订阅后,值从服务器获取为可观察值,我想显示选择字段中的值作为默认值

我尝试了

this.formName.get('controlName').setValue('valueFromServer')

this.formName.get('controlName').patchValue('valueFromServer')

和一些stackoverflow解决方案,但对我来说不起作用。这是我的stackblitz示例。有人可以告诉我这里有什么问题

https://stackblitz.com/edit/angular-izarqy

3 个答案:

答案 0 :(得分:1)

由于<option>的值是整数,因此可以设置选项列表中存在的整数。您尝试设置了字符串'valueFromServer',该字符串在选项列表中不存在,因此不起作用

尝试这样:

 this.tourPageForm.get('accomadation').setValue(1);

注意:如果从服务器获取值,请确保仅在设置值生效后才首先获取选项列表。

答案 1 :(得分:1)

@NicoleZ ..您正在将值设置为正确的形式。

但是,正如@Adrita指出的那样,如果在dropdown 值属性中显示值,Options将选择该值。

看看这个StackBlitz

  

在组件中,

  this.tourPageForm.get('accomadation').setValue('valueFromServer'),
  

在模板中

  <select  style="width:100px" formControlName="accomadation" class="form-control border">
         <option value="valueFromServer">1</option>
  </select>

修改

实际上setValue和patchValue起作用。确认如下

 this.tourPageForm.get('accomadation').setValue('valueFromServer');
 this.tourPageForm.get('mealType').setValue('Value recive from Server');
 console.log(this.tourPageForm.value)

控制台 tourPageForm 时,您将获得以下值。

accomadation: "valueFromServer"
mealType: "Value recive from Server"
transportation: ""

这意味着setValuepatchValue正常工作,但由于dropdown中未显示它们而没有选择表格Options

我希望这会有所帮助..:)

答案 2 :(得分:1)

我遇到了同样的问题,实际上我们需要将来自服务器的值与option中设置的当前值进行匹配,这是一个示例。否则它将无法正常工作。

example.component.html

<select  formControlName="status">
          <option [value]="null">Choose...</option>
          <option value="pending">Pending</option> // only works if setValue('pending')
  </select>

example.component.ts

this.exampleForm.get('status').setValue('pending');