Как анимировать изменение переменной в angular8, которая не является списком? - PullRequest
1 голос
/ 02 марта 2020

У меня есть следующая переменная:

"test", который по умолчанию равен "Some Text"

В моем шаблоне я использую его: {{test}}

Как сделать так, чтобы каждый раз, когда пользователь нажимал кнопку, которая изменяет содержимое переменной «test» (например, «Другой другой текст»), происходило постепенное исчезновение и исчезновение анимации в самом тексте или родительском элементе div ? Большинство примеров, которые я вижу, включает списки ... есть ли способ сделать это без одного?

1 Ответ

1 голос
/ 02 марта 2020

Существует несколько способов анимации текста при его изменении. Но я предпочитаю использовать Angular анимации, поскольку она предоставляет некоторые изящные вспомогательные функции и обратные вызовы событий анимации.

Ниже фрагменты кода анимируют изменение текста с использованием Angular анимаций. Комментарии добавляются в фрагмент кода, чтобы объяснить, что происходит.

Html файл шаблона:

<h1>Angular Animations Example</h1>
<div>
    <label>Name is: </label>
    <span class="text"
      [@animateText]="currentState"
      (@animateText.done)="animationFinished($event)"
    >
      {{ text }}
    </span>
</div>
<br/>
<button (click)="changeText()">Change Text</button>

Файл компонента:

import { Component } from '@angular/core';
import {
  trigger,
  state,
  style,
  transition,
  animate,
  AnimationEvent
} from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    // Define the custom animation trigger
    trigger('animateText', [
      // Defining the hidden state
      state('hidden', style({
        opacity: 0
      })),
      // Defining the visible state
      state('visible', style({
        opacity: 1
      })),
      // Defining the animation for state changes
      transition('hidden <=> visible', [
        animate('1s ease')
      ])
    ])
  ]
})
export class AppComponent  {
  text = 'Angular';

  // Start with hidden state and then change it to visible state 
  // to animate the text when the component is rendered
  currentState = 'hidden';

  changeText() {
    // Do not change the text
    // instead change the state to hidden first for fade away animation

    this.currentState = 'hidden';
  }

  // This method is called when the animation has finished playing
  animationFinished(event: AnimationEvent) {
    if (event.fromState === 'void' && event.toState === 'hidden') {
      /** 
       * This block executes when the component is rendered initially.
       * Change the state to visible once the component has been initialized
       * to play the animation
       */

      this.currentState = 'visible';
    } else if (event.fromState === 'visible' && event.toState === 'hidden') {
      /**
       * Once the previous text fades, perform the text change logic
       * and then change state to visible to play the animation
       */

      this.text = this.text === 'Angular' ? 'Stackblitz' : 'Angular';
      this.currentState = 'visible';
    }
  }
}

Не забудьте включить BrowserAnimationsModule в файл AppModule.

app.module.ts

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";

import { AppComponent } from "./app.component";

@NgModule({
  imports: [BrowserModule, BrowserAnimationsModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Вы можете найти пример, который я создал на Stackblitz здесь . Подробнее о Angular анимациях можно найти здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...