简体   繁体   English

根据 Angular 中的输入更改 select 的选定值

[英]Change the selected value of a select depending on an input in Angular

I have this form.我有这个表格。 Which if the temperature of a person is greater than 38°C degrees the value of a select must change from healthy to sick if it's selected.如果一个人的温度高于 38°C 度,则 select 的值必须从健康变为有病。

<form [formGroup]="form">
  <select formControlName="health" required>
  <option value="HEALTHY">Healthy</option>
  <option value="SICK">Sick</option>
  </select>
  <input (focusout)="changeValue($event)" type="number" 
   formControlName="temperature" required>
  </form>

When it is finished writing the function changeValue is called and this is how I am trying to change the value of the selected option.当它写完 function changeValue 被调用,这就是我试图改变所选选项的值的方式。

ngOnInit() { 
  this.form = this.formBuilder.group({
    health: ["", Validators.required],
    temperature: ["", Validators.required],
})}
change(temperature){
  if(temperature > 38){
     this.form = this.formBuilder.group({
     temperature: ["SICK"],
})}
}

There are some bits you can do better when using reactive forms使用反应式 forms 时,有些位可以做得更好

Check the following检查以下

https://stackblitz.com/edit/angular-ivy-pytdtp https://stackblitz.com/edit/angular-ivy-pytdtp

You need to reference the formControl you want to change directly and use it's.setValue() method.您需要直接引用要更改的 formControl 并使用它的.setValue() 方法。

so in the method you call on change, you can say this.form.get('temperature').setValue('SICK').所以在你调用改变的方法中,你可以说this.form.get('temperature').setValue('SICK').

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM