我正在尝试使用Angular Materials mat-select中的optionSelectionChanges observable属性。它提供了所有子选项更改事件的组合流。
当用户更改选项以更新其上的验证器时,我想获取先前的值。我不知道如何处理从模板到组件的可观察流,或者该属性是否最好?
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>
组件:
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([])]
});
}
}
谢谢
答案 0 :(得分:5)
optionSelectionChanges
是属性而不是输出。它打算从您的脚本代码中使用-我认为您不能从模板中使用它。这是一个示例:
<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)});
}
}