要在Angular Material中使用响应式表单为mat-select选择设置多个默认值,可以使用FormControl的setValue方法来实现。以下是一个示例代码:
在组件的HTML模板中,使用mat-select来创建选择框,并将FormControl与mat-select绑定在一起:
Select Options
{{ option.label }}
在组件的TypeScript文件中,创建一个FormControl,并在组件初始化时使用setValue方法为FormControl设置默认值:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
options = [
{ value: 'option1', label: 'Option 1' },
{ value: 'option2', label: 'Option 2' },
{ value: 'option3', label: 'Option 3' }
];
optionsControl = new FormControl();
ngOnInit() {
// 设置默认值
this.optionsControl.setValue(['option1', 'option3']);
}
}
在上述代码中,options数组包含所有可选择的选项。optionsControl是一个FormControl,用于跟踪mat-select的选择值。在ngOnInit方法中,使用setValue方法将默认值['option1', 'option3']设置为FormControl的值。
这样,当组件加载时,mat-select会显示默认选择的选项。