1

I am using template driven form. Currently i am getting the true or false value. but i need the actual value of checkbox

 <form #f = "ngForm" (ngSubmit) = "onClickSubmit(f.value)">
    <h2 class="no-top-space">
        {{Questions?.Question}}
    </h2>
    <div *ngFor="let op of options">
        <input type="checkbox" name="check" [value]="option.Value" ngModel>{{op.Value}}
    </div>
    <button type="submit" role="button" class="btn btn-primary blue">Submit</button>
</form>



onClickSubmit(data){
    console.log("dataaa",data)
}
Hiren Nakrani
  • 234
  • 3
  • 15
  • if you only can check one check at time: [this SO](https://stackoverflow.com/questions/68190231/cant-bind-to-ngvalue-since-it-isnt-a-known-property-of-input/68191798#68191798), if you can get an array [this another SO](https://stackoverflow.com/questions/63797930/get-multiple-checkbox-value-as-an-array-in-angular/63799360#63799360), and you has another aproach in [this another one](https://stackoverflow.com/questions/50173409/how-to-access-multiple-checkbox-values-in-angular-4-5/64058789#64058789) – Eliseo Aug 06 '21 at 11:56

1 Answers1

0

Try this: In html:

 <input type="checkbox" name="check" [value]="op.Value" ngModel (change)="handleChange($event)">{{op.Value}}

In ts:

declare an array variable which will have a blank array initially. like

selectedOptions:string[]=[] 

Then build the handleChange method as:

handleChange(event:any)
{
    if(this.selectedOptions.length>0)
    {
     let existedOption = this.selectedHobby.findIndex((x) => x === e.target.value); //to check if it is already present in the array or not
          if (existedOption != -1)
           {
                this.selectedOptions.splice(existedOption, 1);
           } 
           else 
           {
              this.selectedOptions.push(e.target.value);
           }
    } 
    else 
    {
          this.selectedOptions.push(e.target.value);
    }
    console.log(this.selectedOptions);
  }