Search code examples
angularangular-forms

defaut value in mat-select always get value in array with index = 1;


I used Comparewith Function in mat-select but i dont know how to change default value in mat-select. It always set first value in array

categoryList: Category[] = [
  { categoryId: 1, categoryName: 'Chemistry' },
  { categoryId: 2, categoryName: 'Math' },
];

This case, value is always 'Chemistry'. How to change default value to Math.

This is code HTML:

<mat-select placeholder="Category" formControlName="categoryId" [compareWith]="compareFn">
    <mat-option *ngFor="let category of categoryList" [value]="category.categoryId">
       {{ category.categoryName }}
    </mat-option>
</mat-select>

compareFn(c1: any, c2: any): boolean {
   return c1 && c2 ? c1.categoryId=== c2.categoryId: c1 === c2;
}

ngOnInit() {
   this.QuestionForm = this.formBuilder.group({
      categoryId: ['']
   });
   this.QuestionForm.get('categoryId').setValue(2);
}

I hope people point out a solution for me. Thanks


Solution

  • Set Different name for formControlName and not the categoryId Which is your property key in an Array. So, Make some changes in your current code like below

    <mat-select placeholder="Category" formControlName="categories">
        <mat-option *ngFor="let category of categoryList" [value]="category">
           {{ category.categoryName }}
        </mat-option>
    </mat-select>
    
    ngOnInit() {
       this.QuestionForm = this.formBuilder.group({
          categories: [null]
       });
    
       const defaultVal = this.categoryList.find(ctgry=> ctgry.id == 2);
       this.QuestionForm.get('categories').setValue(defaultVlue);
    }
    
    and no need for the compare function if you are using it for setting the category. Hope it will be helpful to you.