How to Make CSS Transitions Work with ngIf in Angular 2?

Patricia Arquette
Release: 2024-10-31 21:17:29
Original
985 people have browsed it

How to Make CSS Transitions Work with ngIf in Angular 2?

ngIf and CSS Transition/Animation in Angular 2

Question:

When utilizing ngIf to display a div in Angular 2, why won't CSS transitions work if the element is initially hidden?

Answer:

ngIf removes the element from the DOM when its condition becomes false. However, transitions cannot be applied to non-existent elements.

Solution:

For a smooth transition, use [hidden] instead of [ngIf]:

<code class="typescript"><div class="note" [ngClass]="{'transition':show}" [hidden]="!show"></code>
Copy after login

This way, the element remains in the DOM and transitions can be applied when its show property changes.

Updated Solutions with Angular Animations

In Angular 4.1.0 and 2.1.0, Angular Animations provide an improved way to achieve transitions with ngIf.

Angular 4.1.0 and Later:

<code class="typescript">trigger('enterAnimation', [
  transition(':enter', [
    style({transform: 'translateX(100%)', opacity: 0}),
    animate('500ms', style({transform: 'translateX(0)', opacity: 1}))
  ]),
  transition(':leave', [
    style({transform: 'translateX(0)', opacity: 1}),
    animate('500ms', style({transform: 'translateX(100%)', opacity: 0}))
  ])
])</code>
Copy after login

Angular 2.1.0:

This approach uses the animate() helper that was introduced in 2.1.0. Refer to the Angular animations documentation for more details.

The above is the detailed content of How to Make CSS Transitions Work with ngIf in Angular 2?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!