首页 > 解决方案 > 在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

在这里工作

标签: htmlangulartypescriptcheckboxangular9

解决方案


更新: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


推荐阅读