我的项目中有mat-selection-list,它显示了项目中的角色列表,并以编程方式选择了组中的现有角色。到目前为止,一切都如期而至。
<div *ngIf="group!==undefined" class="col-12" style="margin-top: 30px">
<h4>Group Roles</h4>
<mat-selection-list [compareWith]="roleCompareFn" [formControl]="rolesControl" >
<mat-list-option *ngFor="let role of allRoles" [selected]="doesGroupHasThisRole(role)" [value]="role" checkboxPosition="before" style="font-size: 14px">
{{role.name}}
</mat-list-option>
</mat-selection-list>
<button mat-raised-button color="primary" (click)="getSelectedRoles()">Submit</button>
</div>
<h2>Selected Roles:</h2>
<div *ngFor="let role of selectedRoles" >
{{role.name}}
</div>当单击submit并尝试获取所选角色列表时,我将得到空列表。但是,当我选择/更改任何内容时,我会得到所有选定的角色。在StackBlitz中创建的示例以供参考
发布于 2020-07-15 06:45:34
Jadda,如果您管理多个select,忘记使用选项中的选择。多个选择需要一个存储数组的控件。您可以存储角色数组(然后使用compareWith)或数组(如果是数字,则使用value="roles.id“)。
看看有多简单(请看我们使用value="role.id“
<mat-selection-list [formControl]="rolesControl" >
<mat-list-option *ngFor="let role of allRoles" [value]="role.id">
{{role.name}}
</mat-list-option>
</mat-selection-list>你可以用,例如。
rolesControl =新的FormControl(1,3);/或this.rolesControl.setValue(2,4)
如果您想存储一个角色数组,您需要
<mat-selection-list [formControl]="rolesControl" >
<mat-list-option *ngFor="let role of allRoles" [value]="role">
{{role.name}}
</mat-list-option>
</mat-selection-list>以及,当定义控件的值时
rolesControl = new FormControl([
{id:2,name:"ROLE_SELLER"},
{id:4,name:"ROLE_BUYER"}]);
//or
this.rolesControl.setValue([
{id:2,name:"ROLE_SELLER"},
{id:4,name:"ROLE_BUYER"}]);注意:有时,在.html中写文章很有趣,只是为了检查一下:
<pre>
{{rolesControl?.value|json}}
</pre>NOTE2:在您的代码中,对于不同角色,您具有相同的"id“
https://stackoverflow.com/questions/62904962
复制相似问题