How do I manipulate 3 Checkbox in Angular 2?

Asked

Viewed 1,947 times

0

I have 3 Checkbox. The first option is bread, the second option is fish and the third has salt. I want to use Tamplate Forms and not reactive Forms. Can someone help me?

<form #form="ngForm">
    <label>
        <input name="" type="checkbox">Tem pao</label>
    <label name=""><input type="checkbox">Tem peixe</label>
    <label><input type="checkbox" name=""">Tem sal</label>
    <button type="submit" (click)="enviarPrint(form)">Enviar</button>
</form>

  • but in fact what needs it to return true or false to the backend?

  • @Willian I actually want to return the same names... When you click on Have bread, return to the bank "Have bread". When it is has fish, return to the Bank "Has Fish". When it is has salt the same thing. Can help me ?

  • puts the value in the checkbox axo that resolves... value="has bread", if I am not mistaken when it ta false it does not print the value... if it is true prints the value. or put before sending in the sendPrint() this.opcao2 ? 'has bread' 'has no bread;

2 answers

1

All you need is on this page, what you need is to put the three values in an array and make a *ngFor, at the end you will have an array where each index will have true or false. The sample code of the tutorial is here.

Update: For a Template Form (which will not make sense because there is no difference), just scroll through the form, check if the checkbox is selected and include in the array.

enviarPrint(form: any | FormGroup) {
    this.array = [];
    for (const field in form.controls) {
        const control = form.controls[field];
        if(control.value === true) {
          this.array.push(field);
        }
    }
  // enviar pro back-end
  }

Example in Stackblitz here

  • This method of yours is implementing Reactive Forms and he commented that he is using Template Forms

  • I made an update on the reply, please review the vote made. Thank you for the correction

1


Declare a variable in your Typescript

checks = [
    { id: 1, name: 'check 1', check:"true" },
    { id: 2, name: 'check 2', check:"false" },
    { id: 3, name: 'check 3', check:"false" },
    { id: 4, name: 'check 4', check:"true" }
  ];

And in your HTML use *ngFor

<label *ngFor="let check of checks">
    <input type="checkbox" [checked] = "check.check === 'true'" >
    {{check.name}}
</label>

Browser other questions tagged

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