Reputation: 602
I'm planning to use the below described Angular Material Multi-Select Template to allow the user to select multiple inputs (and use them in a function called with (click), so no real-time-access needed). However it's unclear to me how to access the values the user has selected.
I'm guessing the 'toppings' -FormControl()-Object has something to do with it but it doesn't contain the string-values from the possible options array as expected.
EDIT: Updated Html code below.
Source: 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>
Upvotes: 0
Views: 879
Reputation: 996
Hopefully, this can help..
Change your mat-option [value] to
[value]="availableGenre"
Then add a function in your .ts
click(array) {
console.log('genres:', array)
}
And then a button in the .html
<button (click)="click(genres.value)">Click me</button>
And like joyBlanks says, the values are also available in this.toppings.value
click2() {
console.log('genres:', this.genres.value)
}
<button (click)="click2()">Click me</button>
Upvotes: 1
Reputation: 56
I'm not sure what your trouble is here, but you can access the value of your mat-select with the value attribute :
<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>
Upvotes: 0