[Angular] Two ways to create Angular Animation, using animation() or using state()

We have two blocks to show to difference ways to do animation in Angular:

<button (click)="toggleState()">Toggle</button>

<div style="display: flex; align-items: center; align-content: space-between;">

  <section [@heightZeroFull] *ngIf="state === 'active'" style=" 200px; height: 200px; background: black;">
  </section>

  <section [@heightState]="state" style=" 200px; height: 200px; background: blue;"></section>
</div>

heightZeroFull using animation(). heightState using state().

The way to control the state is:

  state = 'active';

  toggleState() {
    if (this.state === 'inactive') {
      this.state = 'active';
    } else {
      this.state = 'inactive';
    }
  }

In the component, we define 'animations':

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    heightZeroFull({duration: '500ms'}),
    heightState({height: '200px', duration: '500ms'})
  ]
})

We pass in params, so it is more configurable.

Animation.ts:

import {animation, style, animate, trigger, transition, useAnimation, state} from '@angular/animations';

/*
* DSL
* */
const heightStart =  animation([
  style({
    height: 0
  }),
  animate(
    "{{duration}} ease-in",
    style({
      height: '*'
    })
  )
]);

const heightEnd = animation([
  animate(
    "{{duration}} ease-out",
    style({
      height: 0
    })
  )
]);


/*
* Transition
* */
// Using animation
export const heightZeroFull = (params) => {
  return trigger('heightZeroFull', [
    transition(':enter', useAnimation(heightStart, {params})),
    transition(':leave', useAnimation(heightEnd, {params}))
  ]);
};


// Using state
export const heightState = (params) => {
  return trigger('heightState', [
    state('inactive', style({
      height: 0
    })),
    state('active',   style({
      height: params.height
    })),
    transition('inactive => active', animate(`${params.duration} ease-in`)),
    transition('active => inactive', animate(`${params.duration} ease-out`))
  ]);
};
原文地址:https://www.cnblogs.com/Answer1215/p/7242790.html