Home > Article > Web Front-end > How to Make CSS Transitions Work with ngIf 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>
This way, the element remains in the DOM and transitions can be applied when its show property changes.
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>
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!