如何将反应形式绑定到md-select



我有一个简单的反应形式:

this.filterForm = this.fb.group({
'type': ['', [Validators.required]]
});

和角材料元素:

<form [formGroup]="filterForm">
<md-select formControlName="type"></md-select>
</form>

当我订阅更改时:

this.filterForm.valueChanges.subscribe(val => {
console.log(val);
});

它对材料不起作用,我错在哪里?

我也试过这个:

[formControlName]="type"

尝试将所有内容移动到ngOnInit,而不是constructorngOnChanges

原因:constructor应该尽可能轻。并且ngOnChanges@Input属性改变时触发,而不是在form值改变时触发

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'select-value-binding-example',
templateUrl: 'select-value-binding-example.html',
styleUrls: ['select-value-binding-example.css'],
})
export class SelectValueBindingExample {
filterForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.filterForm = this.fb.group({
'type': ['', [Validators.required]]
});
// To change if anything in the form changed.    
this.filterForm.valueChanges.subscribe(val => {
console.log(val);
});
// To change if just type in the form changed.
this.filterForm.get('type').valueChanges.subscribe(val => {
console.log(val);
});
}
}

这是样品StackBlitz供您参考。

尽管我使用的是Angular Material的一个较新版本,但这应该仍然有效。

最新更新