首页 > 解决方案 > 在 ts 文件中显示从 mat-select 多个中选择的值

问题描述

我正在使用多个。我想在控制台中显示选定的值。我正在使用 Angular 6 Material design 我在 html 中获得了价值。但我想在 ts 文件中以逗号分隔所有选定的值。下面是我的代码。

<form [formGroup]="searchUserForm" fxFlex fxLayout="column" autocomplete="off" style="margin: 30px">
    <mat-select placeholder="User Type" formControlName="userType" multiple>
        <mat-option *ngFor="let filters of userTypeFilters" [value]="filters.key" (click)="tosslePerOne(allSelected.viewValue)">
            {{filters.value}}
        </mat-option>
        <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
    </mat-select>
</form>

import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { MatOption } from '@angular/material';

@Component({
  selector: 'material-app',
  templateUrl: 'app.component.html'
})
export class AppComponent { 
  searchUserForm: FormGroup;

  userTypeFilters = [
    {
      key: 1, value: 'Value 1',
    },
    {
      key: 2, value: 'Value 2',
    },
    {
      key: 3, value: 'Value 3',
    },
    {
      key: 4, value: 'Value 4',
    }
  ];
  @ViewChild('allSelected') private allSelected;

  constructor(private fb: FormBuilder){}

  ngOnInit() {
    this.searchUserForm = this.fb.group({
      userType: new FormControl('')
    });
  }
tosslePerOne(all){ 
   if (this.allSelected.selected) {  
    this.allSelected.deselect();
    return false;
}
  if(this.searchUserForm.controls.userType.value.length==this.userTypeFilters.length)
    this.allSelected.select();

}
  toggleAllSelection() {
    if (this.allSelected.selected) {
      this.searchUserForm.controls.userType
        .patchValue([...this.userTypeFilters.map(item => item.key), 0]);
    } else {
      this.searchUserForm.controls.userType.patchValue([]);
    }
  }
}

谁能帮助我如何做到这一点。

标签: angularangular-material-6

解决方案


您应该能够multiple通过this.searchUserForm.get('userType').value.

根据您在 中绑定的内容,valuemat-option将获得一组不同的值/对象。

要获得包括keyand在内的完整对象,请value像这样绑定它[value]="filters"。如果您只需要其中一个属性的数组,请将该属性添加到绑定中。


推荐阅读