Animate ng-container

柔情痞子 提交于 2020-02-25 04:34:39

问题


I'm working on a bigger app, where we are using lazy loading for modules. After we load a module, then in some cases a component get rendered to a <ng-container><ng-container>. The problem is, the animation which is defined on container is not getting called.

I've created a dummy stackblitz example to demonstrate what I mean: link

app.component.html:

<ng-container *ngIf="visible" [@myAnimation]>
    <hello [ngStyle]="{'top': '50px'}" name="not animated"></hello>
</ng-container>

<hello name="animated" [ngStyle]="{'top': '100px'}" *ngIf="visible" [@myAnimation]></hello>

<button (click)="toggle()">Toggle visibility</button>

app.component.ts:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger("myAnimation", [
            transition(":enter", [
                style({opacity: 0 }),
                animate(
                    "800ms",
                    style({
                        opacity: 1
                    })
                ),
            ]),
            transition(":leave", [
                style({opacity: 1 }),
                animate(
                    "800ms",
                    style({
                        opacity: 0
                    })
                ),
            ]),
        ]),
  ]
})
export class AppComponent  {
  name = 'Angular';
  visible = false;

  toggle() {
    this.visible = !this.visible;
  }
}

hello.component.ts:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
}


回答1:


you should give [@myAnimation] in hello component, otherwise it will not possible to grab the animation for hello component from ng-container.

<ng-container *ngIf="visible">
    <hello [ngStyle]="{'top': '50px'}" name="not animated" [@myAnimation]></hello>
</ng-container>

Explanation: From Angular University

ng-container directive provides us with an element that we can attach a structural directive to a section of the page, without having to create an extra element just for that.

We can't use it giving any attribute or adding class, it is used to attach a structural directive. it is documented in Angular

The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

Live example: stackblitz



来源:https://stackoverflow.com/questions/57905975/animate-ng-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!