Search code examples
cssangulartypescriptangular-animations

How to dynamic update angular animation ? (angualr 8)


I'm using the angular animation like this:

@Component({
  selector: 'app-navbar',
  animations: [
    trigger('openClose', [
      // ...
      state(
        'open',
        style({
          height: this.navBarHeight ? this.navBarHeight.toString() + 'px' : '0px',
          opacity: 1,
          backgroundColor: 'yellow',
        }),
      ),
      state(
        'closed',
        style({
          height: '0px',
          opacity: 1,
          backgroundColor: 'green',
        }),
      ),
      transition('open => closed', [animate('0.3s')]),
      transition('closed => open', [animate('0.3s')]),
    ]),
  ],
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss'],
})

export class NavbarComponent implements OnInit {

  public navBarHeight = 0;

 public ngOnInit() {
    this.navBarHeight = this.navBarContainer.nativeElement.offsetHeight;
  }

}

so the element that I want animated has a dynamic height based on the server, so I need to save the origin height when the page is fully loaded.

in ngOnInit I can got the height of the element , but the problem is I got an Cannot read property 'navBarHeight' of undefined when I try to define the animation before I got the height that I wanted.

is there a way to dynamic set the animation settings?


Solution

  • Try setting the height of the element in the template, so you can access the calculated height [ngStyle]="{'height': this.navBarHeight}" and setting the height in the animation as a wildcard style ({ height: '*', ... })