简体   繁体   中英

Animate ng-container

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM