【发布时间】:2021-11-04 03:03:16
【问题描述】:
我正在尝试获取列表顶部的选中复选框 如果我说 选中五个复选框中的第四个复选框(12345)结果 应该是 (41235) 请帮忙参考一下 我已经添加了工作 到目前为止完成并添加链接。
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
【问题讨论】:
标签: html angular typescript checkbox angular9