I am using array of mat-select to display array of object contains some set like:
typesOfAccess = [{1 : 'View Image'},{2 : 'Tag MPxN'},
{3 : 'Configure User'},{4 : 'Assign UserGroup'},
{5:.......},{6:..........}]
I am subscribing data from API who having numbers saved in array with their string value. like below:
this.UserEditForm = this.formBuilder.group({
is2FAEnabled:[''],
AccessRights : ['',Validators.required]
});
I want to display number of the array which i get from api to be pre-selected in HTML.
<mat-selection-list formControlName="AccessRights" (ngModelChange)="onNgModelChange($event)" required>
<mat-list-option *ngFor="let tta of typesOfAccess; let i = index" [value]="i+1" [selected]="AccessRights.option">
{{tta[i+1]}}
</mat-list-option>
</mat-selection-list>
Please help here.
remove the selection property binding and just update the form control value this will reflect to the html element
<mat-selection-list formControlName="AccessRights" >
<mat-list-option *ngFor="let tta of typesOfAccess; let i = index" [value]="i+1">
{{tta[i+1]}}
</mat-list-option>
</mat-selection-list>
set the AccessRights
value when create the form group
this.UserEditForm = this.formBuilder.group({
is2FAEnabled:[''],
AccessRights : ['2',Validators.required]
});
or set the value manually like this
this.UserEditForm.get('AccessRights').setValue('2'); // will select Tag MPxN
Updated 🔥🔥
you need to send an array base of the selected items like [1,3]
this.UserEditForm.get('AccessRights').setValue([1,3]); // 👈
if you want to select a single value justlike this
this.UserEditForm.get('AccessRights').setValue([3]); // 👈