Reputation: 57
I have following angular material select HTML:
<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
MOQALAQEdokumentisTipebi is an array that is getting updated from a network API request. I just want to select by default the first element of 'MOQALAQEdokumentisTipebi' array.
I have tried doing something like this:
<mat-select [(ngModel)]="MOQALAQEdokumentisTipebi[0]" formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
But in this case, I would get the whole array instead of the first element.
I have tried adding default variable in my TS file:
public defValue = MOQALAQEdokumentisTipebi[0];
But in this case, I was getting blank selection, as if there was nothing assigned to it. I also console logged my defValue variable and it showed data, but it didn't work in default selection.
My question is how to set default selection first element of the array in the code like this(with ngFor):
<mat-select formControlName='personPersonDocumentTypes'>
<mat-option *ngFor="let dokumeti of MOQALAQEdokumentisTipebi" [value]="dokumeti">
{{dokumeti}}
</mat-option>
</mat-select>
// adding array of doc types
this.moqalaqeSearchData.personPersonDocumentTypes.map((array) => {
this.MOQALAQEdokumentisTipebi.push(array.personDocumentType.nameGeorgian);
});
Upvotes: 0
Views: 1419
Reputation: 2759
As @Bojan said, you need to set the form value when you receive datas :
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])
}
Upvotes: 1