在Angular 8中,要设置默认选中选项的话,可以使用FormControl
和FormGroup
来创建响应式表单,并使用patchValue
方法来设置默认选中的选项。
下面是一个示例代码:
component.ts:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
favoriteColor: ['blue'] // 设置默认选中的选项
});
}
submitForm() {
console.log(this.myForm.value);
}
}
component.html:
在上述代码中,我们在FormGroup
中使用favoriteColor
作为表单控件的名称,并在构造函数中将其设置为默认选中的选项。
需要注意的是,要使用响应式表单,需要在模块中引入ReactiveFormsModule
。
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
],
declarations: [...],
providers: [...]
})
export class AppModule { }
这样,当表单加载时,favoriteColor
将默认选中为"blue"。