Home > Blockchain >  How do you set the value of a select-options value now that ngModel is deprecated
How do you set the value of a select-options value now that ngModel is deprecated

Time:07-22

Now that ngModel is deprecated in Angular, how do you set the value of the select-options on entering a page.

I'm using a reusable form:

  constructor(public formBuilder: FormBuilder) { 
    this.createProfileForm = this.formBuilder.group({
      gender: new FormControl('', [Validators.required]),
    })
  }

  ngOnInit() {
    this.createProfileForm.patchValue({
      gender: 'Man'
    })
    console.log('form', this.createProfileForm.value);
  }
 <form [formGroup]="createProfileForm">
    <ion-card>
      <ion-select formControlName="gender" placeholder="*Gender">
        <ion-select-option data-cy="gender-dropdown" *ngFor="let genOption of genderOptions"> {{genOption}}</ion-select-option>
      </ion-select>
    <ion-button  expand="full" (click)="addProfile()" [disabled]="!createProfileForm.valid">Submit</ion-button>
  </form>

I can't use ngModel so I'm trying to patch the value but that value doesn't appear on the selection even though I can see the patch value in the console.log

{bio: '', gender: 'Man', education: '', smoking: '', drinking: '', …}
bio: ""
dateOfBirth: ""
drinking: ""
education: ""
gender: "Man"
smoking: ""

So I can customize the options I have the select options as an input on the form component: @Input('genderOptions') genderOptions: string[];

On the page that actually uses the form I'm sending in the genderOptions in the following:

  genderOptions: string[] = ['Woman', 'Man', 'Transgender Woman', 'Transgender Man', 'Non-binary'];
  <app-profile-form [genderOptions]="genderOptions"  (profile)="onSubmit($event)"></app-profile-form>

So when I load the profile page I need to set the value of the gender.

This is one attempt to resolve the issue to no avail:

      <ion-select formControlName="gender" placeholder="*Gender" (change)="valueChanging($event)" [value]='{{Opt}}'>
        <ion-select-option data-cy="gender-dropdown" *ngFor="let genOption of genderOptions"> {{genOption}}</ion-select-option>
      </ion-select>

How exactly do you set the value without using ngModel?

CodePudding user response:

You can set the value of a select element with the help of reactiveforms in Angular.

Below is my attempt to illustrate the following :

  1. How to retrieve the selected value via 'Event Change' and 'Reactive Forms'
  2. How to set the value of a dropdown using 'Reactive Forms' in Angular.

app.component.html

  <hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<form [formGroup]="exampleFormGroup" (ngSubmit)="onSubmit(exampleFormGroup)">
  <select formControlName="exampleSelect" (change)="onChange($event)">
    <option *ngFor="let item of itemList" [value]="item">{{item}}
    </option>
  </select>
  <p>{{selectedValue}}</p>
  <button type="submit">Submit</button>
</form>

app.component.ts

import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular '   VERSION.major;
  exampleFormGroup: FormGroup;
  selectedValue: any = '';
  constructor(public formBuilder: FormBuilder) { 
    this.exampleFormGroup = this.formBuilder.group({
      exampleSelect: new FormControl('', [Validators.required]),
    })
  }
  onChange(event:any){
    console.log(event.target.value);
  }
  itemList=["item1","item2","item3","item4"];

  onSubmit(formData){
    console.log('Form has been submitted!');

    //get the selected value
    console.info(this.exampleFormGroup.controls['exampleSelect'].value);
    
    //set the value
    this.exampleFormGroup.controls['exampleSelect'].setValue('item4');
  }
}
  • For getting the selected value on 'Event change of a drop down' , please refer 'onChange()' method.
  • To get and set the value of a dropdown via reactive form please refer 'onSubmit()' method.

Let me know if this will help by providing your feedback, so that others will get benefitted as well.

I have created a sample project which can be accessed from here!

  • Related