简体   繁体   中英

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.

<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.

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

Check the following

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

You need to reference the formControl you want to change directly and use it's.setValue() method.

so in the method you call on change, you can say this.form.get('temperature').setValue('SICK').

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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