Search code examples
htmlangularcheckboxreturn-valueangular-ngmodel

how to specify the value of our checkbox


I want that when the user checks on checkbox, the value be "l.code" instead of a Boolean value

Here's my code

<div class="form-group">
    <label>Critères : </label>&nbsp;
    <div class="checkbox-inline" *ngFor="let l of lesCriteres; let i= index">
      <label>
        <input type="checkbox" [value]="l.code" [(ngModel)]="actif.lesCriteresActifs[i].critere.code">{{l.code}}
      </label>
    </div>
</div>

But it does not work ! when I check, it gives me "true" instead of "l.code". Thanks !


Solution

  • You can do something like below :

    HTML:

    <div *ngFor="let data of emails">
        <input type="checkbox" [value]="data.email" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
    </div>
    

    ts:

    import { Component } from '@angular/core';
    import { FormGroup, FormBuilder, FormArray, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular 6';
    emailFormArray = [];
      emails = [{ email: "email1" }, { email: "email2" }, { email: "email3" }, { email: 'email4' }]
      myForm: FormGroup;
    
      constructor(private fb: FormBuilder) { }
    
      ngOnInit() {
        this.myForm = this.fb.group({
          useremail: this.fb.array([])
        });
      }
    
      onChange(email: string, isChecked: boolean) {
        if (isChecked) {
          this.emailFormArray.push(email);
        } else {
          let index = this.emailFormArray.findIndex(x =>{ 
            console.log(x);
            return x == email
            });
          console.log(index)
          this.emailFormArray.splice(index,1);
        }
        console.log(this.emailFormArray)
      }
    
    }
    

    STACKBLITZ