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

时间:2018-11-06 18:18:42

标签: angular angular-material angular-reactive-forms

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

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"

1 个答案:

答案 0 :(得分:1)

尝试将所有内容移至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);
    });
  }
}

这是您推荐的Sample StackBlitz

尽管我使用的是Angular Material的更高版本之一,但这仍然可以正常工作。