Angular9及以上版本如何实现勾选的checkbox选项置顶列表头部
实现方案
核心思路是维护勾选顺序的同时,渲染列表时优先展示已勾选项,后勾选的项排在已勾选分组的最前面。
第一步:修改TS文件
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { options = ['1', '2', '3', '4', '5', '6']; selected = []; messages = []; // 新增:返回排序后的渲染列表,已勾选在前,未勾选在后 get sortedOptions() { return [...this.selected, ...this.options.filter(item => !this.selected.includes(item))]; } // 校验项是否已选中 checked(item) { return this.selected.indexOf(item) != -1; } // checkbox状态变更事件 onChange(checked, item) { if (checked) { // 替换push为unshift,后勾选的项排在已勾选列表最前面,匹配预期顺序 this.selected.unshift(item); } else { this.selected.splice(this.selected.indexOf(item), 1); } console.log(this.selected); } save() { this.messages.push(this.selected.sort()); } }
第二步:修改HTML文件
仅需要把列表循环的数据源从options改为新增的sortedOptions即可:
<h1>Angular Checkbox List</h1> <h3>Options</h3> {{options | json}} <h3>Selected</h3> {{selected | json}} <br> <h3>List</h3> <!-- 修改循环绑定的数据源 --> <div *ngFor="let item of sortedOptions"> <input type="checkbox" (change)="onChange($event.target.checked, item)" [checked]="checked(item)" > {{item}} </div> <br> {{selected.length}} items selected <br> <button (click)="save()">Save</button> <h3 *ngIf="messages.length != 0">Log</h3> <div *ngFor="let item of messages"> save: {{item}} </div>
效果验证
按照你给出的测试场景,依次勾选one、three、five,最终渲染顺序为five → three → one → two → four,完全符合预期。
内容的提问来源于stack exchange,提问作者rkamlekar
相关产品推荐
相关产品推荐

