Utilize the animation feature of a single component across various other components in Angular

I've created an animation function in my app.component.ts and now I want to use this same function in other components without repeating the code. Is there a more efficient way to do this?

Here is the code in app.component.ts:

import { Component, OnInit, HostListener, ElementRef } from "@angular/core";
import { trigger, state, style, animate, transition } from 
"@angular/animations";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
  animations: [
    trigger("scrollAnimationMain", [
      state(
        "show",
        style({
          opacity: 1,
          transform: "translateX(0)"
        })
      ),
      state(
        "hide",
        style({
          opacity: 0,
          transform: "translateX(-100%)"
        })
      ),
      transition("show => hide", animate("700ms ease-out")),
      transition("hide => show", animate("700ms ease-in"))
    ]),

    trigger("scrollAnimationSecond", [
      state(
        "show",
        style({
          opacity: 1,
          transform: "translateX(0)"
        })
      ),
      state(
        "hide",
        style({
          opacity: 0,
          transform: "translateX(100%)"
        })
      ),
      transition("show => hide", animate("700ms ease-out")),
      transition("hide => show", animate("700ms ease-in"))
    ])
  ]
})

export class AppComponent {
  state = "hide";

  constructor(public el: ElementRef) {}

  @HostListener("window:scroll", ["$event"])
  checkScroll() {
    const componentPosition = this.el.nativeElement.offsetTop;
    const scrollPosition = window.pageYOffset;

    if (scrollPosition + 700 >= componentPosition) {
     this.state = "show";
    } else {
      this.state = "hide";
    }
  }
}

Now how can I apply this function in time-line.component.ts?

import { Component, OnInit } from '@angular/core';
import { AppComponent } from '../app.component';

@Component({
  selector: 'app-time-line',
  templateUrl: './time-line.component.html',
  styleUrls: ['./time-line.component.css'],
})
export class TimeLineComponent implements OnInit {

  constructor() {
   }

  ngOnInit() {

  }

}

Answer №1

Typically, all animations are organized in one or more files, such as:

animation.main.ts

export const formStateMainTrigger = trigger("scrollAnimationMain", [
  state(
    "show",
    style({
      opacity: 1,
      transform: "translateX(0)"
    })
  ),
  state(
    "hide",
    style({
      opacity: 0,
      transform: "translateX(-100%)"
    })
  ),
  transition("show => hide", animate("700ms ease-out")),
  transition("hide => show", animate("700ms ease-in"))
]);

export const formState2Trigger = trigger("scrollAnimationSecond", [
  state(
    "show",
    style({
        opacity: 1,
        transform: "translateX(0)"
    })
  ),
  state(
    "hide",
      style({
        opacity: 0,
        transform: "translateX(100%)"
      })
    ),
    transition("show => hide", animate("700ms ease-out")),
    transition("hide => show", animate("700ms ease-in"))
]);

You can then import them like this

import { formStateMainTrigger } from './animations.main';
animations: [formStateMainTrigger]

To implement the method inside the component, you could do the following:

export function checkScroll(el) {
    const componentPosition = el.nativeElement.offsetTop;
    const scrollPosition = window.pageYOffset;
    if (scrollPosition + 700 >= componentPosition) {
     return "show";
    } 
    return "hide";
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No updates found (Angular)

When a button is clicked, a test method is triggered with i as the index of an element in an array. The test method then changes the value of the URL (located inside the sMediaData object) to null or '' and sends the entire sMediaData to the pare ...

Preserving the state of an Angular application across page refreshes

What is the best way to maintain state persistence between page reloads? I'm not referring to state management with ngrx, but rather the scenario where refreshing the page causes user logouts, unsaved changes, and other data loss. Initially, I consid ...

Tips for programmatically choosing dropdown menus in Angular 5

Trying to set up a dropdown select option in Angular 5 that dynamically changes based on the backend's input. https://i.sstatic.net/8cgsh.png Keep in mind that both select boxes are identical, only the options inside them vary. selector.html <h ...

Unable to fake a fetch request using the 'fetch-mock-jest 1.5.1' library

I am attempting to simulate a fetch call using thefetch-mock-jest library, but the code continues to try accessing the remote address and ultimately fails with the error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: ...

Deciding between a Template or Component in Angular: What's the best choice?

What is the best approach to decide between using ng-template or a Component in Angular? For instance, if I need to display a UI that will be used in multiple places within the same component, should I opt for a template or create a separate component? & ...

What is the correct way to define functions within an object using Typescript in this situation?

Currently in the process of converting a JavaScript project to TypeScript, I encountered this error message (utilizing urql): A function whose declared type is neither 'void' nor 'any' must return a value. ts(2355) on line: playerCrea ...

Using :global() and custom data attributes to apply styles to dynamically added classes

Currently, I am working on creating a typing game that is reminiscent of monkeytype.com. In this game, every letter is linked to classes that change dynamically from an empty string to either 'correct' or 'incorrect', depending on wheth ...

What is the best way to create an optional object parameter in Typescript?

I'm working on a function that looks like this: const func = (arg1: string, { objArg = true }:{ objArg: string }) => { // some code } Is it possible to make the second parameter (an object) optional? ...

Build the Angular 9 project just once to generate the package output and perform test runs

Currently in our Continuous Integration pipeline, we execute ng test before ng build. However, after upgrading to Angular, we noticed that the full project is being compiled twice - once for the tests and once for the build. This duplication is causing an ...

Determine the function's return type based on its arguments

Here is the code snippet: const handleNodes = (node: Node | Node[]) => { if (Array.isArray(node)) { return [{}]; } return {}; }; The desired result is: handleNodes([{}]) // infer that this returns an array handleNodes({}) // infer that this r ...

The data structure '{ one: string; two: string; three: string; }' cannot be directly assigned to a 'ReactNode'

Here is the Array of Items I need to utilize const prices = [ { name: "Standard", price: "149EGP", features: [ { one: "Add 2500 Orders Monthly", two: "Add Unlimited Products And Categories", three: "Add 20 other ...

Aggregate the data chunks in the antd table into groups

I've been struggling to find a solution for this specific issue. My goal is to group the data in my table based on a particular field, but I need it to be styled as depicted in the image linked below. https://i.stack.imgur.com/OsR7J.png After looking ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...

Creating dynamic lists in Angular with ngFor: A step-by-step guide

I am currently working on an Angular 7 application and have a component that retrieves a JSON array. @Component({ selector: 'app-indices-get', templateUrl: './indices-get.component.html', styleUrls: ['./indices-get.component ...

I am unable to refresh the table data in Angular

Here is the code that I am currently working with: I am facing an issue where my webpage is not updating its data after performing delete or any other operations. The user list is not being displayed in the data. Despite my attempts, I have been unable to ...

The name 'Diagnostics' cannot be located

I've downloaded the Typescript repository and am currently reviewing the code. However, I keep encountering this recurring error message: Cannot find name 'Diagnostics' This error pops up on lines that are similar to this: Diagnostics._ ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

Obtaining a bearer token from Auth0 in an Angular application involves a few

Can someone guide me on obtaining the Auth0 bearer token in Angular when using the Auth0 SDK and AuthModule? @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public auth: AuthService) {} intercept(request: HttpRequ ...

Does a typescript definition file exist for Apple MapKit JS?

Before embarking on creating one, I'm curious if anyone has come across a typescript definition file (.d.ts) for Apple MapKit JS? ...

Converting seconds to days, hours, and seconds using Moment.js in a ReactJS and TypeScript environment

I would like to achieve the following: I have a value in seconds. When I pass this value to the moment function, I expect to receive the corresponding values for days, hours, and seconds. I have utilized moment.js and managed to output logs as well, but I ...