pokly
pokly

Reputation: 121

Angular checkbox changing itself issue

I'm a beginner in Angular. I want to sort a dropdown FormArray alphabetically.

component.html

<label class="custom-control custom-checkbox" *ngFor="let car of carsControls; let i = index" [hidden]="!cars[i]?.show">
  <input type="checkbox" class="custom-control-input" [formControl]="car" />
  <span class="custom-control-label" [innerHTML]="cars[i]?.name"></span>
</label>

component.ts

ngOnInit(){
  this.cars.sort((a, b) => a.name.localeCompare(b.name));
}

My issue is that after submitting a selected checkbox, the selection of the dropdown changes itself. For example: The selected checkbox changes from Mercedes to BMW by itself after I press submit.

EDIT:

I am getting the Controls like this:

get carsControls() {
    return (this.carFormGroup?.get('cars') as 
    FormArray)?.controls;
  }

FormGroup:

carFormGroup = this.formBuilder.group({
    filter: [''],
    cars: this.formBuilder.array([])

Upvotes: 0

Views: 49

Answers (1)

Florent Arlandis
Florent Arlandis

Reputation: 925

Cars are ordered alphabetically but not carsControl. That's your problem, you only have the labels ordered.

Upvotes: 3

Related Questions