Angular 2 ngIf and CSS Transition/Animation: Resolving Transition Issues
With ngIf, it's common to encounter challenges when attempting CSS transitions on elements controlled by the directive. ngIf removes elements from the DOM when its condition becomes false, hindering the ability to apply transitions.
Original Issue
When using ngIf with CSS transitions, the element is hidden initially and transitions won't work.
Solution
Since ngIf removes elements from the DOM, an alternative approach is to use the hidden attribute instead.
Code Sample
<code class="html"><div class="note" [ngClass]="{'transition':show}" [hidden]="!show"> <p> Notes</p> </div></code>
Alternatively, with Angular 4.1.0 and above
Angular animations provide an elegant way to handle such transitions.
Code Sample
<code class="typescript">import { trigger, style, animate, transition } from '@angular/animations'; @Component({ animations: [ 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})) ]) ] ) ], template: ` <button (click)="show = !show">toggle show ({{show}})</button> <div *ngIf="show" [@enterAnimation]>xxx</div> ` }) export class App { show: boolean = false; }</code>
Advantages of Using Animations
The above is the detailed content of How to Achieve Smooth CSS Transitions with Angular 2\'s ngIf?. For more information, please follow other related articles on the PHP Chinese website!