简体   繁体   中英

Why does angular checks/unckecks all my checkboxes?

I'm creating a project on angular 15.1.0 and angular checks or unchecks all checkboxes. I'm using @fullcalendar to show a calendar and when a date is clicked a modal appears with several checkboxes and the checkboxes should be check depending on some backend info and the date selected. When the modal appears its where I find this problem.

My html code:

<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form (ngSubmit)="submit($event)">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="staticBackdropLabel">Selecciona personal que comieron el dia {{fecha | date:'dd/MM/YYYY'}}</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <h5>Personal</h5>
                    <div class="form-group">
                        <div class="form-check" *ngFor="let user of users">
                            <input class="form-check-input" type="checkbox" name="name" [attr.id]="user.no_nomina + 'Checkbox'" [(ngModel)]="user.check">
                            <label class="form-check-label" [attr.for]="user.no_nomina + 'Checkbox'">
                                {{ user.first_name + ' ' + user.last_name + ' ' + user.check}}
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar</button>
                </div>
            </div>
        </form>
    </div>
</div>

My component:

import { DatePipe } from '@angular/common';
import { Component, Input} from '@angular/core';
import {Modal} from 'bootstrap';
import { BackendService } from 'src/app/backend.service';

@Component({
  selector: 'app-modal-comedor',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComedorComponent {
  modalEl:any;
  modal:any;
  users:any[] = [];
  update: boolean = false;

  @Input() fecha?: Date;

  constructor(protected backendService: BackendService) {}

  ngOnInit() {
    this.modalEl = document.querySelector('#staticBackdrop');
    this.modal = new Modal(this.modalEl);
    let user = {
      bd: 'administracion',
      action: 'get',
      table: 'user',
      opts: {},
    };
    this.backendService.post(user).subscribe((u: any) => {
      u.result.forEach((e: any) => {
        e.check = false;
        this.users.push(e);
      });
    });
  }

  ngOnChanges(changes:any){
    if(changes.fecha!==undefined){
      if(changes.fecha.currentValue!==changes.fecha.previousValue){
        let pipe = new DatePipe('en-US');
        let info = {
          bd: 'administracion',
          action: 'get',
          table: 'comedor',
          opts: { where: {fecha:pipe.transform(this.fecha,'yyyy-MM-dd')}},
        };
        this.backendService.post(info).subscribe((result:any)=>{
          this.users.forEach((user:any)=>{
            let index = result.result.findIndex((res:any)=>res.no_nomina==user.no_nomina);
            if(index !== -1){
              user.check = true;
            }else{
              user.check = false;
            }
          });
        });
      }
      this.modal.show();
    }
  }

  submit(event:any){
    return;
    let aux:any[] = [];
    let fechas: any[] = [];
    let pipe:DatePipe = new DatePipe('en-US');
    let fecha = pipe.transform(this.fecha,'yyyy-MM-dd');
    this.users.forEach((e:any)=>{
      if(e.check){
        aux.push(e.no_nomina);
        fechas.push(fecha);
      }
    });
    //ponemos en estado de eliminado las tuplas anteriores
    let eliminar  = {
      bd: 'administracion',
      action: 'update',
      table: 'comedor',
      opts: {attributes: {deleted:'1'},where:{fecha:fecha}},
    };
    this.backendService.post(eliminar).subscribe((result:any)=>{
      //creamos tuplas para la BD
      let info = {
        bd: 'administracion',
        action: 'createSeveral',
        table: 'comedor',
        opts: { attributes: {no_nomina: aux,fecha:fechas}},
      };
      this.backendService.post(info).subscribe();
    });
    this.modal.hide();
  }
}

And when testing the code this happens:

enter image description here

You can also see that the information is correct but the checkboxes doesn't work as expected.

Found the solution to my problem here .

Just had to add the attribute [ngModelOptions]="{standalone: true}".

<input class="form-check-input" type="checkbox" name="name" [attr.id]="'Checkbox' + user.no_nomina" [(ngModel)]="user.check" [ngModelOptions]="{standalone: true}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM