2

Im fairly new to working with angular and was wondering if there is a simple way to first check if the checkbox is selected. If it is selected, I want to pass it to the saveOptions function. If more than one is selected, I would like to pass them all and save them to an array of options. Can someone help me out?

import { Component } from '@angular/core';
import { forEach } from '@angular/router/src/utils/collection';
import { Options } from 'selenium-webdriver/ie';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  options: any = []



  saveOptions(x:any[]){
     x.forEach(element => {
      this.options.push(element);
    });
  }

} 
<ul class="option-row">
    <div class="option-group">
        <li><input type="checkbox"  id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
        <li><input type="checkbox"  id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
        <li><input type="checkbox"  id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
    </div>
    <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
    <button type="button" (click)="saveOptions();">Submit</button>
</ul>
1
  • 1
    You can see this answer. It will better for you. Click here Commented Apr 11, 2019 at 17:12

4 Answers 4

3

One way is subscribing to valueChanges of the form, like this:

export class AppComponent implements OnInit {
  options: any = []
  model = { optionOne: false, optionTwo: false, optionThree: false }
  formChangesSubscription;
  @ViewChild('form') ngForm: NgForm;

  ngOnInit() {
    this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
      console.log(x);
    })
  }

  saveOptions(x: any[]) {
    x.forEach(element => {
      this.options.push(element);
    });
  }
} 
<form #form="ngForm">
    <ul class="option-row">
        <div class="option-group">
            <li><input type="checkbox" [(ngModel)]="model.optionOne" name="optionOne" id="option-1" value="1" required> <label for="option-1">Option 1</label></li>
      <li><input type="checkbox" [(ngModel)]="model.optionTwo" name="optionTwo" id="option-2" value="2" required> <label for="option-2">Option 2</label></li>
      <li><input type="checkbox" [(ngModel)]="model.optionThree" name="optionThree" id="option-3" value="3" required> <label for="option-3">Option 3</label></li>
    </div>
    <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
    <button type="button" (click)="saveOptions();">Submit</button>
</ul>
</form>

https://stackblitz.com/edit/angular-j5idkn?file=src%2Fapp%2Fapp.component.ts

Sign up to request clarification or add additional context in comments.

Comments

1

I am just gonna extend ganesh's answer here!

Component.html

<form #form="ngForm">
     <ul class="option-row">
    <div *ngFor="let li of listedValue; index as i" class="option-group">
        <li><input type="checkbox"  id="option-{{li}}" [value]="l" required (click)="setCheckbox(li, i)"> <label for="option-{{li}}">Option {{ i }}</label></li>
    </div>
        button type="button" (click)="saveOptions();">Submit</button>
</ul>
</form>

component.ts

name = 'Angular 5';
  listedValue: any = [0, 1, 2];
  options: any = []

  ngOnInit(){}

  setCheckbox(event: any, index: number) {
    if(!this.options.includes(event)){
      this.options = [...this.options, event];
    }else {
      this.options = this.options.filter((item) => item !== event);
    }
  }

  saveOptions() {
   console.log(this.options);
  }

StackBlitz

Comments

1

you can this in dynamic way with the help of ngFor and [value] of the div element.

use an array for your li elements, modify your template and component some thing like below.

Component.html

 <ul class="option-row">
    <div *ngFor="let li of listedValue" class="option-group">
        <li><input type="checkbox"  id="option-{{li}}" [value]="l" required (click)="setCheckbox($event,li)"> <label for="option-{{li}}">Option 1</label></li>
    </div>
        <!--Want to know how to check if the checkbox is selected and pass the selected options to the method-->
        <button type="button" (click)="saveOptions();">Submit</button>
</ul>

Component.ts

name = 'Angular 5';
  listedValue: any = [1, 2, 3];
  options: any = []

  setCheckbox(event: any,value: any) {
     if (event.target.checked)
       this.options.push(value)
     else
       this.options= this.options.filter(val => val != value);
  }

  saveOptions() {
   console.log(this.options);
  }

I have created a stackblitz for your case check it once. I hope this will solve your issue :)

2 Comments

this will keep adding to the array on checking and unchecking.
don't get confused between stack and array, js provide stack functions on any array. pop only removes the top element thus output will be different on checking and unchecking and they are not mutation friendly.
0

i think you can use form control reactive form it will help you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.