首页 > 解决方案 > 使用 Angular Material Select 和 Reactive Forms 访问输入

问题描述

我打算使用下面描述的 Angular Material Multi-Select Template 来允许用户选择多个输入(并在一个名为(单击)的函数中使用它们,因此不需要实时访问)。但是,我不清楚如何访问用户选择的值。

我猜 'toppings' -FormControl()-Object 与它有关,但它不包含预期的可能选项数组中的字符串值。
编辑:更新了下面的 Html 代码。

来源:https ://material.angular.io/components/select/overview

//html

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppings" multiple> //?
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</mat-form-field>

//extract from my equivalent
<mat-label>Genres</mat-label>
    <mat-select [formControl]="genres" multiple>
      <mat-option *ngFor="let availableGenre of availableGenres" [disabled] ="disableGenres"  [value]="genre">{{availableGenre}}</mat-option>
    </mat-select>

//ts

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

/** @title Select with multiple selection */
@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  toppings = new FormControl(); //?
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}

//extract from my equivalent in the related component.ts

availableGenres: string[]; //assigned in NgOnInit()
genres = new FormControl();

//update:

<mat-form-field>
  <div>
  <mat-label>Genres</mat-label>
    <mat-select [(value)]="genres" multiple>
      <mat-option *ngFor="let availableGenre of availableGenres" [disabled] ="disableGenres"  [value]="genre">{{availableGenre}}</mat-option>
    </mat-select>
  </div>
</mat-form-field>

标签: javascriptangularangular7

解决方案


希望这可以帮助..

将您的 mat-option [值] 更改为

[value]="availableGenre"

然后在你的 .ts 中添加一个函数

click(array) {
  console.log('genres:', array)
}

然后是 .html 中的一个按钮

<button (click)="click(genres.value)">Click me</button>

就像joyBlanks 说的那样,这些值也可以在 this.toppings.value 中找到

click2() {
  console.log('genres:', this.genres.value)
}
<button (click)="click2()">Click me</button>

推荐阅读