html - 在Angular9及更高版本的列表顶部推送已选中/选中的复选框
问题描述
我正在尝试在列表顶部选择选中的复选框说如果我在五个复选框(123 4 5)中选择了第四个复选框,结果应该是(4 1235)请帮助您参考我已经添加了迄今为止完成的工作并添加链接还。
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 = [];
// check if the item are selected
checked(item) {
if (this.selected.indexOf(item) != -1) {
return true;
}
}
// when checkbox change, add/remove the item from the array
onChange(checked, item) {
if (checked) {
this.selected.push(item);
} else {
this.selected.splice(this.selected.indexOf(item), -1);
}
console.log(this.selected);
}
save() {
this.messages.push(this.selected.sort());
}
}
*** HTML 文件 ***
<h1>Angular Checkbox List</h1>
<h3>Options</h3>
{{options | json}}
<h3>Selected</h3>
{{selected | json}}
<br>
<h3>List</h3>
<div *ngFor="let item of options">
<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 (say I selected first this checkbox) [] two [] three (second this checkbox) [] four [] five (next this checkbox)
异常结果
[]five []three []one []two []four
解决方案
更新:onChange
在方法
中添加这两行
this.options.splice(this.options.indexOf(item), 1);
this.options.unshift(item);
注意: Stackblitz 链接已更新。
旧:
只需.sort()
从行中删除方法this.messages.push(this.selected.sort());
。它将按照您选择它们的顺序给出精确选择的项目。
我已经在您的 Stackblitz 链接中对其进行了修改 - https://stackblitz.com/edit/angular-wmimex
推荐阅读
- javascript - 即使 event.stopPropagation 写在 onClick 处理程序中,事件也会传播到父级
- python - PyPDF2:使用 python3 将输出写入标准输出失败
- javascript - 量角器 - 失败:道具未定义
- arrays - 将充满数据的单个单元格复制到一列?
- node.js - 使用无服务器和 AWS Lambda 的环境变量
- python - 是否可以在 scipy.optimize.linprog 的等式矩阵中包含条件?
- java - 在java中下载图像
- c - 将一个小的正双精度浮点数除以一个大的正数,结果为负
- javascript - 在 d3-tip 中编辑 D3 Tooltip html
- c - 在 Windows 上可以使用环境吗?