Thibault Rouquayrol
Thibault Rouquayrol

Reputation: 11

Ionic 4: How to pre select values in an ion-select component

I am developing an Ionic 4 app. I need to pass data from a list of users to a form in order to modify some attributes of this particular user.

I passed the data from the list (the user) to an other page containing the form. I saved this data in local variables in the .ts of the form.

Now, I have some trouble to make an ion-select component pre-select this data. I have no troubles for an ion-input though.

I tried to do so with a double data binding with [(NgModel)] and a value attribute but it didn't work.

Any help here will be appreciated.

Edit: Here is my code.

The .ts file:

 serviceList: Service[];

 isModifying = false;

 username: string;
 password: string;
 firstName: string;
 lastName: string;
 service: number;
 codivRH: any;
 profil: string;


 constructor(private sqlP: SqlProvider, private route: ActivatedRoute, private router: Router) {

  this.route.queryParams.subscribe(params => {
    if (this.router.getCurrentNavigation().extras.state) {
      this.firstName = this.router.getCurrentNavigation().extras.state.userFirstname;
      this.lastName = this.router.getCurrentNavigation().extras.state.userLastname;
      this.service = this.router.getCurrentNavigation().extras.state.userService;
      this.codivRH = this.router.getCurrentNavigation().extras.state.userCodiv;
      this.profil = this.router.getCurrentNavigation().extras.state.userProfil;
      this.isModifying = true;
    }
  });

}

Here is the .html file:

<ion-item>
          <ion-label> Service </ion-label>
          <ion-select [(ngModel)]="service" name="service">
            <ion-select-option *ngFor="let mservice of serviceList" value="mservice.Id" ngDefaultControl> {{ mservice.Nom }} </ion-select-option>
          </ion-select>
        </ion-item>

        <ion-item>
          <ion-label> CodivRH </ion-label>
          <ion-select [(ngModel)]="codivRH" name="codiv">
            <ion-select-option value="1"> Oui </ion-select-option>
            <ion-select-option value="0"> Non </ion-select-option>
          </ion-select>
        </ion-item>

        <ion-item>
          <ion-label> Profil </ion-label>
          <ion-select [(ngModel)]="profil" name="profil">
            <ion-select-option value="user"> Utilisateur</ion-select-option>
            <ion-select-option value="admin"> Admin </ion-select-option>
            <ion-select-option value="Superadmin"> SuperAdmin </ion-select-option>
          </ion-select>
        </ion-item>

Upvotes: 1

Views: 5530

Answers (2)

cjmm
cjmm

Reputation: 435

I have the same problem using ReactiveForms. Here my form: update.html

 <form *ngIf="datosBasicosForm" name="datosBasicosForm" [formGroup]="datosBasicosForm">
    <ion-list>
        <ion-item>
            <ion-label position="floating">Tipo de Actividad </ion-label>
            <ion-select id="field_tipoDeActividad" placeholder="Seleccionar"   formControlName="tipoDeActividad"
            [compareWith]="compareTipoDeActividad"  >
                <ion-select-option  [value]="tipoDeActividadOption" 
                    *ngFor="let tipoDeActividadOption of tipoDeActividads; trackBy: trackTipoDeActividadById">
                    {{tipoDeActividadOption.nombre}}</ion-select-option>
            </ion-select>
        </ion-item></ion-list></form>

Then in the update.ts I load some data to fill de tipoDeActividads array of TipoDeActividad and the variable actividad of Actividad from the DB with id passed as a parameter:

export class ActividadUpdatePage implements OnInit {

    datosBasicosForm = this.formBuilder.group({
                             id: [],
                             tipoDeActividad: [null, [Validators.required]],
                        });

    async ngOnInit() {

          this.tipoDeActividadService.query()
                .subscribe(data => { this.tipoDeActividads = data.body; }, (error) => 
                  this.onError(error));

          this.activatedRoute.data.subscribe((response) => {
              this.updateForm(response.data);
           });

      }

     updateForm(actividad: Actividad) {
          this.datosBasicosForm.patchValue({
              id: actividad.id,
              tipoDeActividad: actividad.tipoDeActividad, 
      });
}

As you can see I load everything in the ngOnInit and do a patch of the values received in the form.

But even when I click the ion-select and the option is selected, the problem is that it doesn't show the preselected value when the form load...

the compareWith function is as follows:

 compareTipoDeActividad(first: TipoDeActividad, second: TipoDeActividad): boolean {

    return first && second ? first.id === second.id : first === second;

}

So I'm thinking it may be something related to the type of object I'm dealing with? or with the asynchronous load calls that are not ready when the form is rendered?

Any help will be much appreciated, thanks.

Upvotes: 0

Chanaka Weerasinghe
Chanaka Weerasinghe

Reputation: 5742

Here is working example

in your ts

selected;
  defaultList = [
    {
      id: 0,
      key: "BILLPAYMENT",
      value: "Wallet_1002"
    },
    {
      id: 1,
      key: "REQUESTMONEY",
      value: "Wallet_1002"
    },
    {
      id: 2,
      key: "SENDMONEY",
      value: "Wallet_1002"
    },
    {
      id: 3,
      key: "QUICKPAYMENT",
      value: "Wallet_1002"
    }
  ];

  constructor() {

   this.selected={
      id: 0,
      key: "BILLPAYMENT",
      value: "Wallet_1002"
    };
  }

.html

    <ion-item>
        <ion-select [(ngModel)]="selected" [compareWith]="compareFn">
       <ion-option *ngFor="let default of defaultList" [value]="default">{{default.key}}</ion-option> 
     </ion-select>
    </ion-item>

Upvotes: 0

Related Questions