cssangularangular-animations

Angular 17 Animation - Synch both sides on slide left/right


I'm trying to add an animation to the Angular 17 application but it is not working as expected.

There are two divs, side by side, and the left side is hidden by *ngIf when a button is pressed. Animation from the left side works as expected but the right div does not follow, it is resized only when the animation completes.

Here is the sample code: https://stackblitz-starters-uwgcaa.stackblitz.io

How do I make animation work on both sides?

Thanks in advance.


Solution

  • Please change the animation from translateX to margin-left, looked up the CSS tutorials and found the solution!

    import {
      animate,
      group,
      query,
      style,
      transition,
      trigger,
    } from '@angular/animations';
    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    import {
      BrowserAnimationsModule,
      provideAnimations,
    } from '@angular/platform-browser/animations';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <div class="container">
          <div class="menu" *ngIf="showMenu" [@slideInOut]="showMenu">Menu</div>
          <div class="content">Content<button (click)="toggleMenu()">Teste</button></div>
        </div>
      `,
      animations: [
        trigger('slideInOut', [
          transition(':enter', [
            style({ marginLeft: '-100%' }),
            animate('200ms', style({ marginLeft: '0px' })),
          ]),
          transition(':leave', [
            animate('200ms', style({ marginLeft: '-100%' })),
          ]),
        ]),
      ],
      imports: [CommonModule],
    })
    export class App {
      name = 'Angular';
      showMenu = true;
    
      toggleMenu() {
        this.showMenu = !this.showMenu;
      }
    }
    
    bootstrapApplication(App, { providers: [provideAnimations()] });
    

    stackblitz


    References

    1. JSfiddle demo
    2. article