1

I often need to add a setTimeout to make an instruction run the right way with Ionic.

My config :

Ionic:

   ionic (Ionic CLI)  : 4.0.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.1.1
   @ionic/app-scripts : 1.3.7

System:

   NodeJS : v6.10.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/bin/node)
   npm    : 3.10.10
   OS     : macOS High Sierra

My template :

<ion-list [formGroup]="formGroup">

    <ion-item *ngIf="countries">

        <ion-label floating>
            {{ 'customer.country' | translate }}
            <span class="required" ion-text color="red">*</span>
        </ion-label>

        <ion-select formControlName="Country">
            <ion-option *ngFor="let c of countries" [value]="c.In">{{c.Out}}</ion-option>
        </ion-select>

    </ion-item>

For example if I try to set a form control value like this, it will not work properly without a setTimeout:

private setFormControlValue(propertyName: string, value: string, stockEmpty?: boolean): void {

    let formControl: AbstractControl = this.formGroup.controls[propertyName];
    if (_.isEmpty(value) && !stockEmpty) {
        return;
    } else {
        if (!_.isEmpty(formControl) && !_.isNil(formControl)) {
            this.logger.trace('Setting value %s for control : ', value, formControl);
            setTimeout(() => formControl.setValue(value), 100);
        }
    }
}

Also happen when I want to resize my content :

ngOnInit(): void {

    setTimeout(() => this.content.resize(), 100);
}

It even works sometimes with a timeout of '0' ms. I would like to avoid using timeout everywhere but I have the impression Ionic needs the instruction to be run in a different 'thread' to be executed the right way.

If someone does encounter the same issue or know a better workaround I would gladly take it.

Augustin R
  • 7,089
  • 3
  • 26
  • 54
rguerin
  • 2,068
  • 14
  • 29

2 Answers2

2

To my experience, setTimeout would sometimes do the trick regarding to DOM operations and DeviceReady functions. I feel that it's mainly due to Angular's digest-loop performance.

Here's a bit old post of stackoverflow, and it's properly well-written.

Thanks for reading my poor answer.

SuperStar518
  • 2,814
  • 2
  • 20
  • 35
  • It is exactly the same behaviour, I will go on with it. Thank you so much, very interesting reading. – rguerin Oct 11 '18 at 14:12
1

Did you try:

this.formGroup.get('Country').setValue('toto');

Works for me instant

Danel Ceresa
  • 340
  • 2
  • 17
  • Thank you for your answer but my problem is a bit more generic. I made the example with a formGroup but it also happens with other components. I updated my first post. – rguerin Oct 11 '18 at 12:49