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

Abh*_*mar 5 angular-material angular angular-material-6

如何获取从组件中的“ 角材料垫”选择列表选择的所有值的列表。给定的示例显示了要在模板中显示但不在组件中显示的值。我正在尝试修改此问题中给出的解决方案,但对我不起作用。这是我当前的代码:

模板:

<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>
Run Code Online (Sandbox Code Playgroud)

零件:

    onSelection(e, v) {

    console.log(e);
    console.log(v);    
  }
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

解决方案

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

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

Che*_*pan 7

尝试这个

<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>
Run Code Online (Sandbox Code Playgroud)

绑定后,[(ngModel)]="selectedOptions"您可以selectedOptions在组件中使用变量,该变量将包含所有选定的项目。

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


Chi*_*iya 0

我在这里更新了你的 stackblitz 代码https://angular-selection.stackblitz.io

现在您可以在控制台中获取选定的值。

  • 我无法从 stackblitz 获取代码。您可以将代码粘贴到这里吗? (2认同)