从Angular 11开始,formGroup被改为FormGroup,且更名为ReactiveFormsModule。因此,如果您使用的是Angular 11或更新版本,则应使用以下示例中的代码:
在app.module.ts中导入ReactiveFormsModule:
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports
ReactiveFormsModule
],
})
export class AppModule { }
在组件中导入FormGroup:
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
myFormGroup: FormGroup;
ngOnInit() {
this.myFormGroup = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
age: new FormControl('')
});
}
}
此示例创建一个名为myFormGroup的新FormGroup,并向其添加名为firstName,lastName和age的控件。您可以在模板中使用myFormGroup来实现响应式表单。