首页 > 解决方案 > 以角度 8 加载页面后触发动画,ExpressionChangedAfterItHasBeenCheckedError

问题描述

正如问题所暗示的那样,我试图找出一种在页面加载后让元素动画的方法。我到处看了看,但似乎太多了,而且没有办法同时做到这一点,我希望得到一些指导。页面在移动设备中加载后,徽标应缓慢地向右上角设置动画,并且如果有意义的话,还应按比例缩小。

我正在寻找 Angular 等价物$(document).ready(function() {}

根据建议,我已经使用过ngAfterViewInit(),但仍然无法正常工作。

以下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>

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;
    }
  }
}

这是我得到的错误:

在此处输入图像描述

标签: cssangulartypescriptangular8

解决方案


在 component.ts 中设置变量

@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 {

    load_completed = false;

    ngOnInit(){
    }

    ngAfterViewInit(){
      load_completed = true;
    }

}

在你的component.html中

<div [@fadeInOut]="load_completed"> some random element you want to animate  </div>

如上例所示,您可以在需要时根据条件设置动画


推荐阅读