我想要更新表单中的预选选项

I want pre-selected option in the update form already

我正在使用 mat-select 数组来显示对象数组包含一些集合,例如:

typesOfAccess = [{1 : 'View Image'},{2 : 'Tag MPxN'},
{3 : 'Configure User'},{4 : 'Assign UserGroup'},
{5:.......},{6:..........}]

我正在订阅来自 API 的数据,他们将数字及其字符串值保存在数组中。 如下所示:

this.UserEditForm = this.formBuilder.group({
      is2FAEnabled:[''],
      AccessRights : ['',Validators.required]
    });

我想显示我从 api 获得的数组的编号,以便在 HTML 中预 selected。

<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>

请帮忙。

删除 selection 属性 绑定并仅更新表单控件值,这将反映到 html 元素

<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>

创建表单组时设置 AccessRights

this.UserEditForm = this.formBuilder.group({
      is2FAEnabled:[''],
      AccessRights : ['2',Validators.required]
    });

或者像这样手动设置值

this.UserEditForm.get('AccessRights').setValue('2'); // will select Tag MPxN

已更新

您需要发送 selected 项目的数组基数,例如 [1,3]

this.UserEditForm.get('AccessRights').setValue([1,3]); // 

如果你想 select 像这样的单个值

this.UserEditForm.get('AccessRights').setValue([3]); // 

demo

根据 documentation:

The value for each control name is an array containing the initial value as the first item in the array.

您组件中的初始值为 ''。将其更改为您想要的初始值:

AccessRights : [initialValue ,Validators.required]