0

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([])

1 Answer 1

3

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

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

3 Comments

Thank you very much for your help! Do you know how I can do it? I just couldn't figure it out yet...
Just order carsControls. Show me how you built your form.
Thank you, please have a look at my edit. sort() wouldn't work on AbstractControl

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.