Angular 7 动画触发导致控制台错误

Angular 7 animation trigger causes console error

我正在尝试在组件上设置 fadeInOut 动画。 我的应用模块导入了 BrowserAnimationsModule。

我在单独的文件中创建了动画和触发器:

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

export const fadeIn = animation([style({ opacity: 0 }), animate('500ms', style({ opacity: 1 }))]);
export const fadeOut = animation(animate('500ms', style({ opacity: 0 })));

export const fadeInOut = trigger('fadeInOut', [
  transition('void => *', useAnimation(fadeIn)),
  transition('* => void', useAnimation(fadeOut))
]);

然后,我创建了一个组件并验证了该组件本身是否有效:

import { Component, OnInit } from '@angular/core';
import { Globals } from '@app/globals';
import { fadeInOut } from '@app/animations';

@Component({
  selector: 'app-global-alert',
  template: `
    <div class="global-alert" *ngIf="globalAlert">
      <div class="global-alert-message"><ng-content></ng-content></div>
      <div class="close" (click)="closeGlobalAlert()"></div>
    </div>
  `,
  styles: [],
  animations: [fadeInOut]
})
export class GlobalAlertComponent implements OnInit {
  private globalAlert: boolean;

  constructor(private globals: Globals) {
    this.globalAlert = globals.hasGlobalAlert;
  }

  ngOnInit() {}

  closeGlobalAlert() {
    this.globals.hasGlobalAlert = false;
    this.globalAlert = false;
  }
}

请注意,我正在存储此警报是否应出现在 globals.ts 文件中的状态,尽管这无关紧要:

import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  hasGlobalAlert = true;
}

所以我在另一个组件的 html 中使用该组件,如下所示:

<div>
lots of html
</div>
   <app-global-alert>Hello world</app-global-alert>

这有效,当您单击关闭按钮时警报被解除,一切都按预期进行。但是,当我尝试向其中添加触发器时

   <app-global-alert [@fadeInOut]>Hello world</app-global-alert>

我收到一个控制台错误 Error: Found the synthetic property @fadeInOut. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.

我已经用谷歌搜索了这个,但是 AFAICT 我已经涵盖了大多数回复中的所有问题:我已经在组件中包含了 animations 声明,等等。

我错过了什么?

我收到控制台错误错误:Found the synthetic property @fadeInOut. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.

如果您没有在包含模块的组件中导入 "BrowserAnimationsModule" or "NoopAnimationsModule" 模块,就会发生此错误。如果您的动画组件在 App 模块中,则检查 app.module 是否在 @NgModule 中包含以下内容 -

@NgModule({  
  imports: [
    BrowserModule,
    BrowserAnimationsModule //or NoopAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

您需要添加BrowserAnimationsModule 在导入部分的 app-module.ts 文件中。

import: [
BrowserAnimationsModule
]

希望对您有所帮助。 编码愉快:)

如官方所述docs,应将动画添加到组件的元数据中属性。这里 GlobalAlertComponent 中有这样的 属性:

@Component({
  animations: [fadeInOut],
  ...
})
export class GlobalAlertComponent implements OnInit {
...

这允许在此组件的 html 部分内的任何元素上使用动画。但是 @fadeInOut 动画已经在另一个组件的 html 这里使用了:

<div>
  lots of html
</div>
  <app-global-alert [@fadeInOut]>Hello world</app-global-alert>

确保此组件的元数据中包含导入和动画 属性。