Animating the height property in Angular 2 with precise timing during data binding

Seeking a way to have a component called information-board that animates away after a few seconds, I decided on making it slide up as an exit animation. My plan is to achieve this using CSS animations as discussed in this thread: Angular 2 Slide Up and Down Animation

The SCSS code for my info-board component is quite simple:

.info-board {
  transition: height 1s;
  overflow: hidden;
}

An issue arises from the statement made in the aforementioned thread: The height set to 'auto' cannot be animated. While this makes sense, it poses a problem for me because my information-board needs to be a shared component that can start off invisible and only appear when triggered by certain events.

Looking at the HTML structure of my component:

<div *ngIf="informationMessage">
  <div #contentElement class="info-board" [style.height]="contentHeight">
    <alert type="{{alertType}}">
      <strong>{{ informationHeading }}</strong> {{ informationMessage.messageText }}
    </alert>
  </div>
</div>

It's a fairly straightforward setup: If the informationMessage data transfer object (dto) is available, display the component. I use binding to dynamically set the height for proper animation. However, the tricky part comes in when the info-board is initially hidden. In this case, I need to wait for the DTO to be set and the HTML to be rendered. So far, the "afterViewChecked" hook has been used for this purpose, resulting in the following code:

@ViewChild('contentElement') public contentElement: ElementRef;

  ngAfterViewChecked(): void {
    this.checkSetBoardSize();
  }

  private checkSetBoardSize() {
    if (this.contentElement && this.contentElement.nativeElement) {
      this.contentHeight = this.contentElement.nativeElement.scrollHeight + 'px';
    }
  }

This event seems to ensure that ViewChild is properly set, but it might be too late in the rendering process. As it's the final step in the change tracking logic, the height value I set could potentially be ignored. Another option that looked promising was "ngAfterContentChecked," but in that event, ViewChild is not yet set. I also explored ways to trigger a re-render of the change tracking or tried the method mentioned in Angular 2 @ViewChild in *ngIf with ViewChildren without success.

Could there be some other approach I'm missing? While I understand that relying on nativeElements may not be ideal, it seems necessary for handling dynamic heights based on my research.

Answer №1

If you're looking to incorporate animations in your Angular project, the animation feature is a great tool to explore. Check out the example that fits your case in the Angular documentation.

It's important to note that with the upcoming release of Angular version >4.0.0-rc.1, changes are being made to how the animation package (now found in @angular/animations) is utilized. For more information, refer to the changelog for Angular.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

Using Bootstrap's collapse class with a smooth linear transition

I've been attempting to implement Bootstrap collapse with a linear effect, but have been encountering challenges. After trying different versions of Bootstrap, I found that the transitions were quite similar. I decided to go with the latest version av ...

What are alternative methods for creating a table layout without relying on traditional table elements?

Is there a way to eliminate tables from my code and achieve the same layout in the name of progress and learning? Here is an example of the table I currently have: <table cellspacing="0px"> <tr> <td> <img src= ...

Tips for utilizing window.scrollTo in order to scroll inside an element:

I'm experiencing an issue where I have a vertical scrollbar for the entire page, and within that, there's an element (let's call it 'content') with a max-height and overflow-y scroll. The 'content' element contains child ...

Prevent the content within a Bootstrap "row" from moving to a new line

My website appears differently in desktop and mobile view. https://i.sstatic.net/MGJSk.png While the tags align perfectly on desktop, they overflow onto a new line in the mobile view. Specifically, #pytorch and #tensorflow are pushed to a new line which ...

Launching Angular Application on GitHub Pages

I am encountering an issue with my GitHub Pages website that is connected to a custom domain. My domain is hosting a web application created with Angular, but I am having trouble loading the .js and .css files when I visit the site. In the DevTools/Networ ...

Utilizing Vue's string-based class binding feature?

Can Vue class binding work with strings? For example: <div :class={open: target == 'myString'}></div> var app = new Vue({ target: null }) It works when I don't use quotes <div :class={open: target == myString}></div ...

Tips for preventing the larger background from displaying a scroll on a web page

Specifically tailored for this specific page: I am looking to eliminate the scrollbar at the bottom of the browser, similar to how it appears on this page: Thank you ...

How can we adjust the flex values to ensure the label displays properly on a narrow container width?

The labels in the left column of the form are initially sized correctly, but shrink when there is not enough room. However, there's a discrepancy in label size between rows with 2 items and rows with 3 items. body { font-family: Arial; font-siz ...

Tips for transferring JSON data into an array in Angular

How can I pass JSON data retrieved from an API into an array and then display that information in my template? I'm not sure how to accomplish this task. An error is appearing on my console, you can view it here. This is my TypeScript file: this.api. ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

Dimensions of images on Read the Docs (small image widths)

Using MkDocs along with the Read the Docs theme, I am facing an issue with small images not scaling properly on mobile devices. It seems like this problem is related to the CSS of Read the Docs theme, but I'm unsure how to override the default behavi ...

Bracketing the Webpage: A Display of Unique Design

Currently, I am utilizing the Brackets code editor to create a webpage in HTML format. My aim is to transfer these files to another computer so that the user on that device can view the webpage created from these HTML files. Strangely, when I open the HTML ...

Formatting code within an HTML document

I am attempting to customize a stock widget that I obtained from financialcontent.com. My current approach involves using Bootstrap for styling purposes. To incorporate the widget into a div, I found it necessary to embed the script directly within the HT ...

Implementing JavaScript functionality with CSS and HTML on a menu

I'm experiencing issues with my website's menu functionality. Currently, the submenu dropdown works fine, but the main menu is not functional. How can I enable it on the main menu as well? document.addEventListener('click', function( ...

Steps to alter background image and adjust its height upon function activation

I am working on a search page with an advanced search option that only certain users can access. I need the height of my div to increase accordingly and also change the background image to a larger size when the advanced search is selected. How can I make ...

Is there a way to move the bootstrap carousel item captions outside of the image without having to set a specific height for the carousel manually?

<div id="carouselExampleIndicators" className="carousel slide" data-bs-ride="true"> <div className="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" className="active" ...

Aligning the title vertically in Ionic on Android device

Currently, I am in the process of developing an application using the Ionic framework and cordova. After uploading my app for testing purposes, I encountered a small issue. The title in the top bar on Android appears to be misaligned vertically. Is there a ...

Is it possible to apply CSS to the alert and confirm functions in Angular?

Currently, I am facing an issue with implementing CSS on elements that are nested inside a function. I am unsure of how to access them properly. For example: updateUser() { this.usersService.UpdateUser(this.user.id, this.user) .subscribe(() =& ...