如何使用Angular 5的Animate模块切换登录/注册表单
用Angular 5 Animation模块实现登录/注册表单切换动画
没问题!我帮你把原来的jQuery切换逻辑改成Angular 5的Animation模块实现,完美匹配你的需求:默认显示登录表单,点击按钮时带高度和透明度的缓动动画切换表单,完全替代$('form').animate({ height: 'toggle', opacity: 'toggle' }, 'slow');的效果。
步骤1:导入Angular动画模块
首先要确保你的项目已经引入了动画模块,在app.module.ts里添加:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule // 必须导入这个才能启用动画功能 ], // ...其他模块配置 }) export class AppModule { }
步骤2:在组件中定义动画触发器
在你的表单组件(比如auth.component.ts)里,定义控制表单显示/隐藏的动画,对应高度和透明度的切换逻辑:
import { Component } from '@angular/core'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app-auth', templateUrl: './auth.component.html', animations: [ trigger('toggleForm', [ // 表单隐藏时的状态(对应jQuery的toggle隐藏效果) state('hidden', style({ height: '0', opacity: 0, overflow: 'hidden' // 防止表单内容溢出到页面 })), // 表单显示时的状态(对应jQuery的toggle显示效果) state('visible', style({ height: '*', // 自动适配表单内容高度 opacity: 1, overflow: 'visible' })), // 双向切换动画,时长对应jQuery的'slow'(约300ms) transition('hidden <=> visible', animate('300ms ease-in-out')) ]) ] }) export class AuthComponent { // 默认显示登录表单 isLoginFormVisible = true; toggleForm() { this.isLoginFormVisible = !this.isLoginFormVisible; } }
步骤3:编写模板代码
在组件的HTML模板里,把两个表单绑定到动画触发器,同时让按钮文本随表单状态切换:
<!-- 登录表单:默认显示 --> <form class="login" [@toggleForm]="isLoginFormVisible ? 'visible' : 'hidden'"> <h3>登录表单</h3> <!-- 登录表单字段 --> <input type="email" placeholder="邮箱" /> <input type="password" placeholder="密码" /> <button type="submit">登录</button> <!-- 切换到注册表单的按钮 --> <button type="button" (click)="toggleForm()">创建账户</button> </form> <!-- 注册表单:默认隐藏 --> <form class="register" [@toggleForm]="!isLoginFormVisible ? 'visible' : 'hidden'"> <h3>注册表单</h3> <!-- 注册表单字段 --> <input type="text" placeholder="用户名" /> <input type="email" placeholder="邮箱" /> <input type="password" placeholder="密码" /> <button type="submit">注册</button> <!-- 切换到登录表单的按钮 --> <button type="button" (click)="toggleForm()">已有账户?登录</button> </form>
小提示
- 动画里的
height: '*'会自动适应表单的内容高度,比固定值更灵活,和jQuery的height: 'toggle'效果完全一致 overflow: 'hidden'是为了防止隐藏状态下的表单内容溢出到页面上- 如果需要调整动画速度,直接修改
animate()里的时长即可,比如'500ms'会比默认的300ms更慢
这样一来,点击按钮就能看到和原来jQuery一样的平滑切换动画,而且完全遵循Angular的框架规范,不需要直接操作DOM~
内容的提问来源于stack exchange,提问作者Mogan Rangan
相关产品推荐
相关产品推荐

