2

I'm trying to make the option appear selected in Ionic Select using the formControl, however it is not working, the value is set in the form, when I type console.log (this.form) the value of the field appears, but it does not appear in the select , is blank.

I'm using ionic 4 version.

enter image description here

HTML:

<!-- Analysis Mode -->
<ion-col size="12">
  <ion-label class="custom-label" stacked>Modo de Análise</ion-label>
  <ion-select formControlName="analysis_mode" interface="popover">
    <ion-select-option value="1">Aleatório</ion-select-option>
    <ion-select-option value="2">Sequencial</ion-select-option>
  </ion-select>
 </ion-col>

Form:

this.form = this.formBuilder.group({
  analysis_mode: new FormControl(null, Validators.required),
  value: new FormControl(null, Validators.required),
});


this.form.controls['analysis_mode'].setValue(1);
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Vinicius Aquino
  • 697
  • 13
  • 27

1 Answers1

8

You can try this code:

this.form = this.formBuilder.group({
    analysis_mode: new FormControl('defaultValue', Validators.required),
    value: new FormControl('defaultValue', Validators.required),
});

or you can do it after:

this.form.patchValue({
    'analysis_mode': 'defaultValue'
});
Dmitry Grinko
  • 13,806
  • 14
  • 62
  • 86
  • This form is for editing, so I wanted to set it right after the form was created, since I'm looking for the data in the API and displaying it in the form, can I use the second option? – Vinicius Aquino Mar 26 '19 at 17:46
  • 1
    @viniciussvl yes. – Dmitry Grinko Mar 26 '19 at 17:48
  • It worked, but I had to put the integer values, it can not compare string? For example, in html I put [value]="1" instead of value="1" – Vinicius Aquino Mar 26 '19 at 18:05
  • 1
    I can't see your logic and what you are trying to do but you can take a look on this question https://stackoverflow.com/questions/47011521/angular-4-select-default-value-in-dropdown-reactive-forms – Dmitry Grinko Mar 26 '19 at 18:14