可以通过使用patchValue()
方法来设置mat-select
的值。下面是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-myComponent',
templateUrl: './myComponent.component.html',
styleUrls: ['./myComponent.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
option: ['option2'] // 设置初始值为option2
});
}
setOptionValue() {
this.myForm.patchValue({
option: 'option3' // 设置为option3
});
}
}
在上述代码中,我们首先定义了一个myForm
表单,并在初始化时设置了option
字段的初始值为option2
。然后,我们通过patchValue()
方法将option
字段的值设置为option3
。在HTML模板中,我们使用formControlName
将mat-select
与option
字段关联起来,这样mat-select
的值就会自动更新为option3
。
你可以根据自己的需求进一步修改和扩展这个示例。