在Angular Material中,要使用响应式表单从服务中设置值到mat-select,可以按照以下步骤进行。
首先,在组件中创建一个响应式表单,并导入FormControl,FormGroup和FormBuilder。
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
myForm: FormGroup;
options: string[] = ['Option 1', 'Option 2', 'Option 3'];
selectedOption: string = '';
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
option: new FormControl('')
});
// 从服务中获取选项值,并设置到表单控件中
this.myForm.get('option').setValue(this.options[1]);
}
}
接下来,在模板中使用mat-select来显示下拉选项,并将formControlName绑定到响应式表单控件。
通过在组件的ngOnInit方法中使用setValue方法,可以从服务中获取选项值,并将其设置到表单控件中。在上面的示例中,我们将第二个选项设置为默认选中的选项。
这样,当组件初始化时,mat-select将显示从服务中获取的默认选项值。