Issue
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?
Solution
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>