How to Activate Animation Post-Page Load in Angular 8, Overcoming ExpressionChangedAfterItHasBeenCheckedError

Trying to solve a crucial question concerning animating an element after the page has fully loaded. Despite extensive research, I have yet to find a simple and efficient solution. Can anyone offer some advice? Once the mobile page is loaded, I want the logo to smoothly move towards the top-right corner while simultaneously decreasing in size.

I am seeking the Angular equivalent of $(document).ready(function() {}

Although I tried using ngAfterViewInit(), nothing seems to be working as intended.

Here's the content of index-section.component.html

<section class="index-section">
  <div [@logoMoveResize]="load_completed ? 'initial' : 'end'" class="index-logo-wrapper" [class.hideOnLoad]="isTrue">
    <figure>
      <img src="assets/icons/logo_mobile.svg" alt="urbanwheels logo">
    </figure>
  </div>
  <div class="index-media-wrapper">
    <div class="media-container">
      <iframe src="https://player.vimeo.com/video/128014070?autoplay=1&color=ffffff&title=0&byline=0&portrait=0" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>
    </div>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Itaque contra est, ac dicitis; Duo Reges: constructio interrete. Videsne quam sit magna dissensio?
    </p>
  </div>
</section>

As for the index-section.component.ts

import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import { trigger, state, animate, style, group, query, transition } from '@angular/animations';

@Component({
  selector: 'app-index-section',
  templateUrl: './index-section.component.html',
  styleUrls: ['./index-section.component.scss'],
  animations: [
    trigger('logoMoveResize', [
      state('initial', style({
        transform: 'translateX(0%) translateY(0%) scale(1)',
      })),
      state('end', style({
        transform: 'translateX(25%) translateY(-25%) scale(.3)',
      })),
      transition('initial <=> end', [animate('1s')]),
    ])
  ]
})
export class IndexSectionComponent implements OnInit {

  load_completed = true;
  innerWidth: any;

  ngOnInit() {
    this.innerWidth = window.innerWidth;
  }

  ngAfterViewInit() {
    if ( this.innerWidth < 1000 ) {
     this.load_completed = false;
    }
  }
}

Encountering an error message:

https://i.sstatic.net/DjtjA.png

Answer №1

assign a value to a variable in component.ts file

@Component({
  selector: 'app-some',
  templateUrl: './some.component.html',
  styleUrls: ['./some.component.scss'],
  animations: [
    trigger('fadeInOut', [
      state('void', style({
        opacity: 0
      })),
      transition('void <=> *', animate(1000)),
    ]),
    trigger('EnterLeave', [
      state('flyIn', style({ transform: 'translateX(0)' })),
      transition(':enter', [
        style({ transform: 'translateX(-100%)' }),
        animate('0.5s 300ms ease-in')
      ]),
      transition(':leave', [
        animate('0.3s ease-out', style({ transform: 'translateX(100%)' }))
      ])
    ])
  ]
})

export class SomeComponent implements OnInit {

    completed_loading = false;

    ngOnInit(){
    }

    ngAfterViewInit(){
      completed_loading = true;
    }

}

Add the following code snippet in your component.html file

<div [@fadeInOut]="completed_loading"> element you want to animate goes here</div>

By following the example above, you can easily apply animation effects based on certain conditions when needed.

Answer №2

This response has given me the information I needed concerning the query at hand. As per the suggestion of @Kevin LeStarge, my workaround was:

setTimeout(()=> {
    this.load_completed = true;
}, 0);

Alternatively, following @Lijo's advice, using the AfterContentChecked lifecycle hook is another option:

import { ChangeDetectorRef, AfterContentChecked } from '@angular/core';

constructor(
private cdref: ChangeDetectorRef) { }

ngAfterContentChecked() {
this.cdref.detectChanges();
this.load_completed = true;
}

Answer №3

Implementing animation on an element in Angular can be achieved by utilizing the ngAfterViewInit hook.

Answer №4

I am searching for the Angular version of $(document).ready(function() {}

the similar code snippet in Angular would be

constructor(private zone: NgZone) {
  this.zone.onStable.pipe(
    // ensure one-time execution
    first()
  ).subscribe(() => /* perform actions when zone is stable */)
}

Answer №5

Utilizing Angular Resolve means implementing an interface that allows classes to act as data providers. These data provider classes can assist the router in resolving data while navigating through the application. By defining a resolve() method within the interface, this method will be called at the start of navigation, ensuring that the router waits for the data to be resolved before activating the route.

For more in-depth information, you can visit - https://angular.io/api/router/Resolve

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

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

Trying to customize the appearance of vaadin-date-picker's text input

My goal is to make the input text turn red when the date picker is within an element with the class 'has-Error'. Below is an example of what I tried on my index.html page, but unfortunately it didn't work: <style is="custom-style"> ...

What could be causing TypeScript to raise an issue when a /// reference comes after the 'use strict' statement?

This particular inquiry is somewhat connected to a question I posted on Stack Overflow yesterday about why TypeScript is encountering issues when trying to import a module. The initial configuration remains unchanged. My TypeScript file appears as follows ...

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

The Angular Component I've created is displaying a single set of data on each mat-tab screen

I have developed a component with the file name hukamnama-sahib.component.html, which looks like this: <body *ngFor="let dataitem of HukamnamaSahibList"> <h4> <span class="gurmukhi">{{dataitem.line.gurmukhi.unico ...

Are there any React-UI libraries that come with a stylish green color scheme?

Currently working on a small React site and deciding on a UI library. While I do like Material UI and Bootstrap, I find that they have limited default themes available. I am looking for libraries with green-color-based themes or ones that make it easy to ...

Aligning labels vertically with inputs

How can I align all my input fields (image) to the same vertical line? I tried using the vertical-align css property and a sass mixin I found (see below), but neither seemed to work. @mixin vertical-align($pos) { position: $pos; top: 50%; -we ...

Sync HTML Videos

Issue: I am currently developing a 3 column layout where certain columns need to remain sticky at the top of the viewport. In one section, I want to use the same video as a background for all 3 columns, with the specific effect of having the middle column ...

Retrieving information as the user navigates to the next page

Currently, I am using an API endpoint that retrieves over 1000 data objects and delivers them to the user. I believe this method is not efficient since only 30 objects are displayed at once. Is there a more efficient way to load these objects, perhaps in ...

The compilation fails when using TestUtils findRenderedComponentWithType with a Component<Props> definition

Content of the file package.json: { "scripts": { "test": "tsc --project . --noEmit" }, "dependencies": { "@types/react": "^16.7.6", "@types/react-dom": "^16.0.9", "react": "^16.6.3", "react-dom": "^16.6.3", "typescript": "^3. ...

What is the most effective way to organize a collection according to the specific order specified in another array?

I have an array of objects, with each element containing another nested object like this: data = [ { name: "A", type: "AA", children: [ { id: 1, name: "Child-A", admin: ["Y"] }], other: "NA" }, { name: "B", type: "BB", ch ...

Stop removing event triggers when the close button on toastr is clicked

Incorporating toastr.js into my application has presented a unique challenge. When a user submits a form, I want to display a toast notification and provide them with a brief window of time to close the toast by clicking a button before sending the data to ...

The mobile menu is not responding to the click event

Upon clicking the mobile menu hamburger button, I am experiencing a lack of response. I expected the hamburger menu to transition and display the mobile menu, but it seems that neither action is being triggered. Even though I can confirm that my javascrip ...

Angular encountering issue with HTTP service not functioning as expected

I have been encountering issues while trying to retrieve data using JSONPlaceholder in my service. Despite my efforts, I have not been successful in fetching any data. I would greatly appreciate any assistance in resolving this matter. user.component.html ...

What could cause my arguments to "not align with any signature" of console.log?

Here is a basic class example: export class Logger { constructor(private name: string) {} debug(...args: any[]) { console.debug(...args) } log(...args: any[]) { console.log(...args) } } Despite being able to pass anything to console.l ...

Managing API responses using Redux and Typescript

As a beginner in Typescript, I am struggling to integrate Redux with it. The documentation on using Redux with Typescript is confusing me. I am attempting to fetch data and dispatch it to my reducer for future use, just as I did before adopting Typescript ...

The NativeScript Angular side drawer is mysteriously missing, no error messages to be found

I'm currently working on developing a native application with Angular in NativeScript. My goal is to implement the side drawer from Telerik-UI as a filtering panel for the data I plan to present in the main text content area. The issue I'm facing ...

The incorrect child output is causing the observable to trigger erroneously, resulting in the observable receiving inaccurate

For quite some time now, I've been struggling to identify the issue in my code. The scenario is that I have a child component acting as a modal, which includes a search bar. When the user interacts with the search bar, it triggers an event to the pare ...

The alignment of flexNav.js submenus is not consistent

I'm looking to implement the Flex Navigation plugin for a responsive menu. Although the plugin functions properly, I'm encountering an issue with the alignment of submenus under their respective parent items. You can view the problematic behavi ...

Tips on how to efficiently wrap content within a column layout, and to seamlessly shrink it if necessary

I recently encountered an issue where I am attempting to create a three-column layout with each column filled with a dynamic number of divs (boxes) ranging from 5 to 15, each with its own height based on its content. These divs are expected to: 1) Be dis ...