我有一个简单的反应形式:
this.filterForm = this.fb.group({
'type': ['', [Validators.required]]
});
和Angular Material元素:
<form [formGroup]="filterForm">
<md-select formControlName="type"></md-select>
</form>
当我订阅更改时:
this.filterForm.valueChanges.subscribe(val => {
console.log(val);
});
它不适用于材料,我该怎么办?
我也尝试过这个:
[formControlName]="type"
答案 0 :(得分:1)
尝试将所有内容移至ngOnInit
而不是constructor
和ngOnChanges
。
原因: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);
});
}
}
这是您推荐的Sample StackBlitz。
尽管我使用的是Angular Material的更高版本之一,但这仍然可以正常工作。