Nicholas
Nicholas

Reputation: 1143

How to use stream of change events in mat-select?

I am trying to use the optionSelectionChanges observable property in Angular Materials mat-select. It gives a combined stream of all of the child options' change events.

I want to get the previous value when a user changes the option to update validators on it. I don't know how to handle observable streams from the template to the component or if this property is best to do it?

html:

<mat-form-field>
  <mat-select (optionSelectionChanges)='getStream' formControlName='value1'>
    <mat-option value='1'>Option1</mat-option>
    <mat-option value='2'>Option2</mat-option>   
  </mat-select>
</mat-form-field>

Component:

import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { MatOptionSelectionChange } from '@angular/material';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {  
  form: FormGroup;
  getStream: Observable<MatOptionSelectionChange>;

  constructor(private _fb: FormBuilder) { }

  ngOnInit() {
    this.getStream.subscribe(res => {console.log(res)})

    this.form = this._fb.group({
      'value1': [null, Validators.compose([])]
    });
  }
}

Thanks

Upvotes: 2

Views: 6054

Answers (1)

G. Tranter
G. Tranter

Reputation: 17918

optionSelectionChanges is a property not an Output. It is meant to be used from your script code - I don't think you can use it from the template. Here's an example:

<mat-select #select="matSelect" formControlName='value1'>
    <mat-option value='1'>Option1</mat-option>
    <mat-option value='2'>Option2</mat-option>   
</mat-select>

import { AfterViewInit, Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { MatSelect} from '@angular/material/select';

@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})
export class TestComponent implements AfterViewInit, OnInit {

    @ViewChild('select') select: MatSelect;  

    form: FormGroup;

    constructor(private _fb: FormBuilder) { }

    ngOnInit() {
        this.form = this._fb.group({
            'value1': [null, Validators.compose([])]
        });
    }

    ngAfterViewInit() {
        this.select.optionSelectionChanges.subscribe(res => {console.log(res)});
    }
}

Upvotes: 9

Related Questions