使用 Angular Material Select 和 Reactive Forms 访问输入

Accessing inputs with Angular Material Select and Reactive Forms

我打算使用下面描述的 Angular Material Multi-Select 模板来允许用户 select 多个输入(并在调用的函数中使用它们(点击), 所以不需要实时访问)。但是我不清楚如何访问用户 selected.

的值

我猜 '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>

我不确定你的问题出在哪里,但你可以使用 value 属性访问 mat-select 的值:

<mat-form-field>
  <mat-label>{{selectLabel}}</mat-label>
  <mat-select [(value)]="selectValue">
    <mat-option *ngFor="let c of config" [value]="c">
      {{c.label}}
    </mat-option>
  </mat-select>
</mat-form-field>

希望这可以帮助..

将您的 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>