【问题标题】:Accessing inputs with Angular Material Select and Reactive Forms使用 Angular Material Select 和 Reactive Forms 访问输入
【发布时间】:2019-08-27 07:41:17
【问题描述】:

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

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

【问题讨论】:

  • this.toppings.value
  • @joyBlanks 不知何故,尽管选择的数量正确,但所有数组元素都未定义。知道是什么原因造成的吗?

标签: javascript angular angular7


【解决方案1】:

希望这能有所帮助..

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

【讨论】:

  • 将 mat-option 中的 [value] 从流派更改为 availableGenre 解决了未定义值的问题。非常感谢。
【解决方案2】:

我不确定你的问题是什么,但你可以使用 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>

【讨论】:

  • 我更新了我的解决方案,但是,传递给数组的值仍然未定义。请注意,我尝试了两种方法,将流派定义为字符串数组和 FormControl 对象。
猜你喜欢
  • 2018-10-14
  • 2019-01-04
  • 2021-10-05
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多