0

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?

Shinji035
  • 331
  • 2
  • 6
  • 17
  • in fact I gave this.navBarHeight a default value. but I think animation setting is before that, angular can't find navBarHeight property that defined in `export class NavbarComponent implements OnInit ` – Shinji035 Jul 05 '19 at 11:19

2 Answers2

0

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: '*', ... })

rpajo
  • 71
  • 3
0

I found a easy way to do this is use AUTO_STYLE , just import it form angular :import { AUTO_STYLE} from '@angular/animations';

and use it :

 animations: [
    trigger('openClose', [
      // ...
      state(
        'open',
        style({
          // height: this.navBarHeight.toString() + 'px',
          height: AUTO_STYLE,
          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')]),
    ]),
  ],
Shinji035
  • 331
  • 2
  • 6
  • 17