mardi 7 septembre 2021

Push the checked/selected item of checkbox at the top of the list in Angular9 and above

I am trying to get the selected checkbox on the top the list Say If I selected fourth checkbox among five checkboxes(12345) the result should be (41235) please help for your reference I have added work done till now and add link also.

TS file

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 File ***

<h1>Angular Checkbox List</h1>

<h3>Options</h3>

<h3>Selected</h3>

<br>
<h3>List</h3>
<div *ngFor="let item of options">
  <input type="checkbox"
  (change)="onChange($event.target.checked, item)"
  [checked]="checked(item)"
>
  
</div>
<br>
 items selected <br>
<button (click)="save()">Save</button>

<h3 *ngIf="messages.length != 0">Log</h3>
<div *ngFor="let item of messages">
  save: 
</div>

list given

[] one (say I selected first this checkbox)
[] two 
[] three (second this checkbox)
[] four
[] five (next this checkbox)

excepted resulted

[]five
[]three
[]one
[]two
[]four

working here stackblitz




Aucun commentaire:

Enregistrer un commentaire