When I Select A Checkbox All Are Selected (Only The Chosen Must Be Checked)

Asked

Viewed 37 times

-1

When I select a Checkbox all of them are selected, I need only the chosen Checkbox to be selected.

Can you help me? Thank you!

table.component.html:

    <table class="table">
    
    <thead class="thead-dark">
      <tr>
        <th>ID</th>
        <th scope="col">Titulo</th>
        <th scope="col">Descricao</th>
        <th scope="col">Valor</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let livro of livros">
        <th scope="row">
          <div class="form-control">
            <input  type="checkbox" [(ngModel)]="isActive" name="id" value="{{livro.id}}">
            {{livro.id}}
          </div>
        </th>
        <td>{{livro.titulo}}</td>
        <td>{{livro.descricao}}</td>
        <td>{{livro.preco}}</td>
      </tr>
    </tbody>
  </table>

table.componentts.:

import { Component, Input, OnInit } from '@angular/core';
import { LivrosModel } from '../../models/livros-model/livros-model';
//Imports de Services
import { LivrosService } from '../../services/livros.service';
@Component({
  selector: 'app-tabela',
  templateUrl: './tabela.component.html',
  styleUrls: ['./tabela.component.css']
})
export class TabelaComponent implements OnInit {


  livro: LivrosModel = new LivrosModel();
  livros: Array<any> = new Array();
  @Input() isActive: any | undefined;

  constructor(private livrosService: LivrosService) { 
  }

  ngOnInit(): void {
    this.listarLivros();
  }

  // Método para Listar os Produtos:
  listarLivros(){
    this.livrosService.livrosList()
    .subscribe(resposta => {
      this.livros = resposta;
      console.log('Lista de Livros:', this.livros);
    },
    () => { 
      console.log('Falha ao Listar Livros');
    }
    );
  }
// Método para excluir os Produtos:
  removerLivros(){
    console.log('Item Marcado:', this.isActive);
  };
}

1 answer

0


Well, I figured out why.

Basically when I’m assigning the [(ngModel)] for all Checkboxs that are created within my table, and when I change the value of isActive I end up changing for everyone.

The Solution found was to use Formgroup and use formControlName to recover the value of my Checkbox.

So what I did was:

Create a Formgroup

formulario!: FormGroup;

Build it inside my ngOnInit

this.formulario = this.formBuilder.group({
  check: [null]
});

Assign my Formgroup to the form:

<form [formGroup]="formulario">

Pass Formcontrolname inside my Checkbox Input

<td><input type="checkbox" formControlName="check"></td>

With this I can get the True and False value of the Checkbox without checking all boxes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.