2

I fetched the checkboxes names from database, put them in array so they look like this:

pets = ['dog', 'hamster', 'cat', 'parrot']

Then I display them on my view in the following manner:

<div *ngFor='let pet of pets'>
  <input type='checkbox'
     name='pets'
     value='{{pet}}'
  />
  {{pet}}
</div>

So now the question is how can I collect only checked values so that I can send those to the server?

0

1 Answer 1

1

I suggest you to use an array of objects instead of array, because I think it will be barely impossible or very hard to achieve exactly what you want.

We can make a following variable:

pets = [{key: 'dog', isChecked: false}, {key: 'hamster', isChecked: false}, {key: 'cat', isChecked: false}];

And connect every object with ngModel, which will hold the value of each checkbox.

<div *ngFor='let pet of pets'>
    <input type='checkbox'
     name='pets'
     value='{{pet}}'
     [(ngModel)]='pet.isChecked'
     (change)='check()'
    />
    {{pet.key}} - {{pet.isChecked}}
</div>

When user checks any of the chechboxes, it's value will turn to true, and basing on this value, an array of checked elements will be shown.

check(){
   this.arr = [];
   this.pets.forEach(v => v.isChecked ? this.arr.push(v.key) : v);
}

Plunker link

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

1 Comment

@BillyLogan Cheers!

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.