mat-select 中的默认值总是在索引 = 1 的数组中获取值;

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

我在 mat-select 中使用了 Comparewith 函数,但我不知道如何更改 mat-select 中的默认值。它总是在数组

中设置第一个值
categoryList: Category[] = [
  { categoryId: 1, categoryName: 'Chemistry' },
  { categoryId: 2, categoryName: 'Math' },
];

这种情况下,值总是'Chemistry'。如何将默认值更改为 Math.

这是代码 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);
}

希望大家给我指出解决办法。谢谢

this.QuestionForm.controls['categoryId'].setValue(2);

更改上面的行。或者

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

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.