prolina
prolina

Reputation: 325

Angular 2 Animation - boolean trigger

I have a form with one field and if that field is incorrect I want to shake it using animations

<form [formGroup]="subscribeFormGroup">
    <mat-form-field [@error]="isError" class="al-subscribe-form-field">
            <input formControlName="email" matInput type="email">
            <mat-icon class="al-subscribe-icon" svgIcon="mail" (click)="onSubscribeClick()"></mat-icon>
    </mat-form-field>
</form>


animations: [
    trigger('error', [
        transition('false <=> true', useAnimation(shake)),
    ]),
],

public onSubscribeClick(): void {
        if (this.subscribeFormGroup.invalid) {
            this.isError = true;
        }
    ...
}

Now it triggers only at first time when I try to send incorrect data, if I click button the second time etc, the field is not shaking

Upvotes: 1

Views: 263

Answers (2)

Eliseo
Eliseo

Reputation: 57971

Another way -better than setTimeout- is use the animation callback done

<mat-form-field [@error]="isError" 
                (@error.done)="isError = false"
                class="al-subscribe-form-field">
...
</mat-form>

Upvotes: 4

Barremian
Barremian

Reputation: 31115

You need to set the isError to false after each animation cycle. If not the transition false <=> true will never trigger since the isError is still true. Try the following

public onSubscribeClick(): void {
  if (this.subscribeFormGroup.invalid) {
    this.isError = true;
    setTimeout(() => { this.isError = false }, 1000);    // <-- set the duration to the animation duration
  }
  ...
}

Upvotes: 1

Related Questions