How do I manipulate 3 Checkbox in Angular 2?

0

I have 3 Checkboxes. 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>
    
asked by anonymous 29.09.2018 / 18:27

2 answers

0

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>
    
02.10.2018 / 16:37
1

All you need is on this page , what you need is 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 tutorial code is here .

Update: For a Template Form (which will not make sense because it has no difference), simply scroll through the form, check if the checkbox is selected and include it 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 on StackBlitz here

    
01.10.2018 / 01:02