javascript - 使用 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>
解决方案
希望这可以帮助..
将您的 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>
推荐阅读
- javascript - 使用javascript设置两个动画之间的时间延迟
- ubuntu-16.04 - libxml2,libxml2-dev 已安装但仍无法在 ubuntu 中配置
- xamarin.forms - 如何在 xamarin.forms 中为日期选择器实现自定义渲染器?
- java - REST API POST 请求和响应
- c++ - 是否可以在 64 位系统中使用 c++11 为图形创建位邻接数组
- node.js - 我应该在没有 javascript 文件中添加什么来在 Node.js 中创建可执行文件?
- r - 在一个范围内生成 rnorm() 数据
- netlogo - Netlogo,将变量分配给邻居
- php - 外键记录多条时,如何显示一次用户信息?
- spring-boot - 如何使用 MockMVC 和 StandaloneSetup 而没有 WebApplicationContext 测试 Thymeleaf?