从Angular 6 mat-selection-list获取选定值的列表

时间:2018-09-12 05:54:45

标签: angular angular-material angular-material-6

如何获取从组件中的Angular材质mat selection list中选择的所有值的列表。给定的示例显示了要在模板中显示但不在组件中显示的值。我正在尝试修改this question中提供的解决方案,但对我而言不起作用。这是我当前的代码:

模板:

<mat-selection-list #selected [(ngModel)]="readingTypesSelected" (ngModelChange)="onSelection($event)" >
  <mat-list-option *ngFor="let readingType of readingTypes">
    {{readingType.name}}
  </mat-list-option>
</mat-selection-list>

组件:

    onSelection(e, v) {

    console.log(e);
    console.log(v);    
  }

以下内容已登录到控制台:

enter image description here

如何从中提取所选选项的实际值?

解决方案

模板代码的前两行应为(如接受的解决方案中的stackblitz链接中所述):

<mat-selection-list #selected (selectionChange)="onSelection($event, selected.selectedOptions.selected)" >
      <mat-list-option *ngFor="let readingType of readingTypes" [value] ="readingType">

3 个答案:

答案 0 :(得分:1)

尝试一下

luvit/timer

绑定<mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)"> <mat-list-option *ngFor="let shoe of typesOfShoes" [value]="shoe"> {{shoe}} </mat-list-option> </mat-selection-list> 后,您可以在组件中使用[(ngModel)]="selectedOptions"变量,该变量将具有所有选定项。

示例:https://stackblitz.com/edit/angular-hdmfwi

答案 1 :(得分:1)

缺少您的代码值属性

替换

使用

,然后在readingTypesSelected中获取选定的数组,

在[[ngModel)] =“ readingTypesSelected”中提到了

readingTypesSelected“

答案 2 :(得分:0)

return await http.post(
        fullUrl, 
        body:data, // data is your normal json data as a string, 
        headers: {
          'Content-type' : 'text/xml',
        }
    );

在Angular 10中测试。主要部分是<mat-selection-list #products [(ngModel)]="selectedProducts"> <mat-list-option *ngFor="let eachProduct of allProducts;" [value]="eachProduct"> {{eachProduct.name}} </mat-list-option> </mat-selection-list> {{selectedProducts|json}} ,否则它将显示[value]="eachProduct"