0

I tried to select all options of a multi select box using a checkbox. The code is shown below :

    <div class="col-md-6">
    <div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input" (change)="selectAll($event)">
    <label class="custom-control-label" >Select all</label>
    </div>
    
    <select multiple class="form-control multi-select" formControlName="product">
    <ng-container *ngFor="let product of productList" >
                                        
    <option [ngValue]="product.id" [selected]="selected">{{product.name}}</option>  
    </ng-container>
   </select>
    </div>

In ts :

selectAll(e){ 
    if (e.target.checked) {
      this.selected = true;
    } else{
      this.selected = false;
    }
    
  }

The above code shows all options as selected but when we submit the form its value is not getting in the ts. How can I solve this issue?

1 Answer 1

1

Try like this :

form: FormGroup;

selectAll(e){ 
  if (e.target.checked) {
     this.form.get('product').setValue(this.productList.map(({ id }) => id));
  } else{
     this.form.reset([]);
  }
}
<select multiple class="form-control multi-select" formControlName="product">
  <option
    *ngFor="let product of productList"
    [value]="product.id">{{ product.name }}
  </option>  
</select>
Sign up to request clarification or add additional context in comments.

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.