1

I'm using Angular 6.

I have more than 100 items in an array which I have to display in a table. The first element of the table is the checkbox to select the field.

For that checkbox input field I have created a formGroup

exportForm: FormGroup;
processedItems: Array<any> = [];

ngOnInit() {
    this.exportForm = this.formBuilder.group({
      product_index: new FormControl([])
    });
}                                                

and in template

<form [formGroup]="" method="post" (submit)="onSubmit()">
  <table>
    <tr *ngFor="let p of processedItems; let id = index">
      <td>
        {{ id+1 }} <input class="" type="checkbox" formControlName="product_index" title="select" value="{{ id }}">
      </td>
      <td> {{ p.title }}</td>
    </tr>
  </table>
</form>

onSubmit() handler.

onSubmit() {
  console.log(this.exportForm.value);
}

But this only gives one item with false

enter image description here

I want to get value of the selected checkbox.

1 Answer 1

1

Try this

onSubmit() {
  const selectedOrderValue = this.exportForm.value.product_index
      .map((v, i) => v ? this.processedItems[i].value : null)
      .filter(v => v !== null);
}

Ref This:https://coryrylan.com/blog/creating-a-dynamic-checkbox-list-in-angular

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

5 Comments

console.log(selectedOrderValue) is giving a blank array with length 0. I'm afraid if I'm doing it correct?. In the reference example there are predefined values and *ngFor is iterating throw those values. I do not have values to set to form instead want multiple input fields with blank value to the size of the processedItems.
I saw the example and want exactly same as it is. But I do not have data to create controls.
Then how are you populating the check box
you can see implementation in the question.
why are you using formControl instead of formArray do you have any specific reason?

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.