如何将反应形式绑定到 md-select?
How bind reactive form to md-select?
我有一个简单的反应形式:
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);
});
它不适用于 material,我错了什么?
我也试过这个:
[formControlName]="type"
尝试将所有内容移至 ngOnInit
而不是 constructor
和 ngOnChanges
。
原因:constructor
s 应该尽可能轻。并且 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 的较新版本之一,但它应该仍然有效。
我有一个简单的反应形式:
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);
});
它不适用于 material,我错了什么?
我也试过这个:
[formControlName]="type"
尝试将所有内容移至 ngOnInit
而不是 constructor
和 ngOnChanges
。
原因:constructor
s 应该尽可能轻。并且 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 的较新版本之一,但它应该仍然有效。