Search code examples
htmlangularangular-ui-bootstrap

add a Toggle effect with a duration on div for collapse/animation


I want to add an animation/transition on height 0 - auto on a div. I want to make a toggle effect on click. I have built it but the problem is I want to show div in beginning as soon as it displays, currently I have div hidden and it toggles on click. I want it to display content and hide on click but right now its hidden and it comes on click. Here is the code below. Thanks for help in advance. And the plunker

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `<h1>Angular 2 Systemjs start</h1>
    <button type="button" class="btn btn-primary"
      (click)="height = height ? 0 : el.scrollHeight">Toggle collapse
    </button>

    <div       
      class="card card-block card-header block" [style.height]="height + 'px'" #el> 
      <div class="well well-lg">Some content</div>
    </div>
  `,
  styles: [`
    .block {
      overflow: hidden;
      -webkit-transition: height .5s;
      transition: height .5s;
    }
  `]
})
export class App {
  height = 0;
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Solution

  • You can work around that by giving height a proper initial value equal to the height of the element. To determine the height of the element dynamically, use:

    @ViewChild('el') el: ElementRef;
    ngAfterViewInit() {
      setTimeout(() => this.height = this.el.nativeElement.scrollHeight, 0);
    }
    

    Put this inside your component class.

    Note: I am using setTimeout because otherwise angular complains about value being changed after it was checked. I am not 100% clear on why that is, but this is the accepted workaround for that.