angular2--怎么实现多选功能

实现效果如下,实现多选和取消的功能:
在这里插入图片描述
这里我定义一个数组为labelLists,用来存放上面列举的标签,数据格式如下,其中isSelect为标识该标签是否已选:
在这里插入图片描述
html:
html页面使用*ngFor来循环遍历数组;[ngClass]为动态添加一个点击后的active样式,判断条件为当前点击的标签的isSelect属性为true;(click)事件就来做具体的点击效果切换。

<ul>
	<li *ngFor="let list of labelLists" [ngClass]="{'active':list.id==list.id&&list.isSelect==true}" (click)="chooseLabel(list.id)">{{list.name}}</li>
</ul>

ts:

chooseLabel(id) {
	//id为当前点击的id
	//循环遍历一次数组
	for(let i=0;i<this.labelLists.length;i++){
		//在数据里匹配到当前点击的id,如果它的isSelect为false就改为true,反之同理。
		if(this.labelLists[i].id==id&&this.labelLists[i].isSelect==false){
			this.labelLists[i].isSelect=true;
		}else if(this.labelLists[i].id==id&&this.labelLists[i].isSelect==true){
			this.labelLists[i].isSelect=false;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/Ariel_201311/article/details/86161386
今日推荐