Search code examples
ionic-frameworkionic3angular-animations

angular animation in ionic with trigger on keyboard event not working properly


In my Ionic application I need to animate the ion-content element with Angular animation when the keyboard appear/disappear.

I have the following code:

<ion-content padding [@shiftContent]="isKeyboardOpen">

and

@Component({
  selector: 'page',
  templateUrl: 'page.html',
  animations: [
    trigger('shiftContent', [
      state('0', style({
        top: '0px'
      })),
      state('1', style({
        top: "-200px"
      })),
      transition('* <=> *', animate('50ms')),
    ])
  ]
})

and

  ionViewDidEnter() {

    this.keyboardOpenObs = this.keyboard.onKeyboardShow().subscribe(() => {
      this.isKeyboardOpen = true;
    });
    this.keyboardCloseObs = this.keyboard.onKeyboardHide().subscribe(() => {
      this.isKeyboardOpen = false;
    });
  }

When the page load and I open the keyboard for the first time nothing happen, then when I close the keyboard it start working but in the opposite direction (if I open I get the closing animation and vice versa).

The same setup works great if I control the variable with a button instead of the keyboard event.

The listener to the keyboard open/close works, I tried by logging the variable on the keyboard event.


Solution

  • I solved it in this way:

    In my template:

    <ion-content [@shiftContent]="isKeyboardOpen">

    and on every input that triggers the keyboard

              <ion-input
                value=""
                type="text"
                placeholder="Email"
                (ionFocus)="onKeyboardStateChange(true)"
                (ionBlur)="onKeyboardStateChange(false)">
              </ion-input>

    then, in the page decorator inside the controller I have the animation:

      animations: [
        trigger('shiftContent', [
          state('0', style({
            top: '0px'
          })),
          state('1', style({
            top: "-150px"
          })),
          transition('* <=> *', animate('200ms')),
        ])
      ]

    then the method to trigger the animation:

      onKeyboardStateChange(event) {
          if (event) {
            this.isKeyboardOpen = true;
          }
          else {
            this.isKeyboardOpen = false;
          }
        
      }

    Basically, instead of relying on the keyboard's event "onKeyboardShow" and "onKeyboardHide", I trigger the animation when the input gets focused. It is clearly a workaround but in my case it solved the problem.