[英]Angular Material Select - default value selected from array
我有以下 angular 材料 select HTML:
<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
MOQALAQEdokumentisTipebi 是一個從網絡 API 請求更新的數組。 我只想 select 默認情況下是“MOQALAQEdokumentisTipebi”數組的第一個元素。
我試過做這樣的事情:
<mat-select [(ngModel)]="MOQALAQEdokumentisTipebi[0]" formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
但在這種情況下,我會得到整個數組而不是第一個元素。
我嘗試在我的 TS 文件中添加默認變量:
public defValue = MOQALAQEdokumentisTipebi[0];
但在這種情況下,我得到了空白選擇,好像沒有分配任何東西。 我還控制台記錄了我的 defValue 變量並顯示了數據,但它在默認選擇中不起作用。
我的問題是如何在這樣的代碼中設置數組的默認選擇第一個元素(使用 ngFor):
<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
// 添加文檔類型數組
this.moqalaqeSearchData.personPersonDocumentTypes.map((array) => {
this.MOQALAQEdokumentisTipebi.push(array.personDocumentType.nameGeorgian);
});
正如@Bojan 所說,您需要在接收數據時設置表單值:
form: FormGroup;
constructor() {
this.form = new FormGroup({
personPersonDocumentTypes: [''],
// ...
});
this.moqalaqeSearchData.personPersonDocumentTypes.map((array) => {
this.MOQALAQEdokumentisTipebi.push(array.personDocumentType.nameGeorgian);
});
this.form.get('personPersonDocumentTypes').patchValue(this.MOQALAQEdokumentisTipebi[0])
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.