我在mat-select中使用了Comparewith Function,但是我不知道如何在mat-select中更改默认值。它总是在数组中设置第一个值
mod
在这种情况下,值始终为“化学”。如何将默认值更改为数学。
这是代码HTML:
categoryList: Category[] = [
{ categoryId: 1, categoryName: 'Chemistry' },
{ categoryId: 2, categoryName: 'Math' },
];
我希望人们为我指出一个解决方案。谢谢
答案 0 :(得分:0)
this.QuestionForm.controls['categoryId'].setValue(2);
更改上面的行。或
this.QuestionForm = this.formBuilder.group({
categoryId: [2]
});
答案 1 :(得分:0)
为formControlName设置其他名称,而不是categoryId,这是您在Array中的属性键。因此,请像下面这样在当前代码中进行一些更改
<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.