AngularJS2中一种button切换效果的实现方法(二)
- 作者: 无聊95170962
- 来源: 51数据库
- 2021-07-31

之前用三目表达式和ng-class实现了按钮切换效果,似乎达到了我的预期,但是我觉得还有改进空间,网上找了一些资料,大概还有以下几种实现方式:
路由
<button class="btn1" routerlink="component1" routerlinkactive="active" type="submit">btn1</button> <button class="btn2" routerlink="component2" routerlinkactive="active" type="submit">btn2</button>
.active {
background-color: white;
}
将button切换的页面写成一个component,通过routerlink链接到对应的component并显示出来,routerlinkactive来控制路由链接激活后button的样式应用的class。
但是这个有局限性,适合button按下去后,整个页面会有大幅变化的应用场景,那么还有其他方法吗?答案是肯定的。
[class]与(click)
还是通过ngclass和ngclick配合,不过方法和之前写的略有不同。
字符串数组形式
<button [class]="{true:'btn1',false:'btn2'}[ischange]" (click)="ischange=true">btn1</button>
<button [class]="{false:'btn1',true:'btn2'}[ischange]" (click)="ischange=false" >btn2</button>
.btn1{
width: 120px;
height: 43px;
border: 1px solid #eeeeee;
background: white;
border-bottom: none;
text-align: center;
}
.btn2{
border: 1px solid #eeeeee;
border-top: 2px solid #238ff9;
width: 120px;
height: 42px;
background: white;
border-bottom: none;
text-align: center;
}
字符串数组形式是针对class简单变化,具有排斥性的变化,true是什么class,false是什么class。若要设置初识状态的class,可以在component中的构造函数中预先赋值。
对象key/value处理
<button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[ischange]" (click)="ischange='one'">btn1</button>
<button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[ischange]" (click)="ischange='two'">btn2</button>
<button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[ischange]" (click)="ischange='three'">btn3</button>
<button [class]="{'one':'btn1','two':'btn2','three':'btn3','four':'btn4'}[ischange]" (click)="ischange='four'">btn4</button>
这种方法可以对多个对象赋不同的class。或者可以实现多个button互斥性变化:
<button [class]="{'one':'btn1','two':'btn2','three':'btn2','four':'btn2'}[ischange]" (click)="ischange='one'">btn1</button>
<button [class]="{'one':'btn2','two':'btn1','three':'btn2','four':'btn2'}[ischange]" (click)="ischange='two'">btn2</button>
<button [class]="{'one':'btn2','two':'btn2','three':'btn1','four':'btn2'}[ischange]" (click)="ischange='three'">btn3</button>
<button [class]="{'one':'btn2','two':'btn2','three':'btn2','four':'btn1'}[
以上所述是小编给大家介绍的angularjs2中一种button切换效果的实现方法(二),希望对大家有所帮助
推荐阅读
热点文章
Angular中响应式表单的三种更新值方法详析
7
Angularjs实现下拉框联动的示例代码
7
详解AngularJS跨页面传值(ui-router)
2
详解AngularJS1.x学习directive 中‘& ’‘=’ ‘@’符号的区别使用
3
angular2路由切换改变页面title的示例代码
4
Angular2 组件间通过@Input @Output通讯示例
5
Angularjs中ng-repeat的简单实例
3
AngularJS 中ui-view传参的实例详解
4
浅谈Angular路由守卫
4
详解基于Angular4+ server render(服务端渲染)开发教程
4
