如何使用Angular在ngOnInit()处设置FormGroup和FormControl?
我刚刚开始学习角度,旧版本应该可以:如何使用Angular在ngOnInit()处设置FormGroup和FormControl?,angular,typescript,form-control,Angular,Typescript,Form Control,我刚刚开始学习角度,旧版本应该可以: import {Component, OnInit} from '@angular/core' import {FormGroup, FormControl, Validators} from '@angular/forms' @Component({ selector: 'app-login-page', templateUrl: './login-page.component.html', styleUrls: ['./login-page
import {Component, OnInit} from '@angular/core'
import {FormGroup, FormControl, Validators} from '@angular/forms'
@Component({
selector: 'app-login-page',
templateUrl: './login-page.component.html',
styleUrls: ['./login-page.component.css']
})
export class LoginPageComponent implements OnInit {
form: FormGroup
constructor() {
}
ngOnInit() {
this.form = new FormGroup(controls:{
email: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.email]),
password: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.minLength(minLength: 6)])
})
}
onSubmit() {
}
}
错误:
Failed to compile.
src/app/login-page/login-page.component.ts:17:39 - error TS1005: ',' expected. this.form = new FormGroup(controls:{
src/app/login-page/login-page.component.ts:18:39 - error TS1005: ',' expected. email: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.email]),
src/app/login-page/login-page.component.ts:18:62 - error TS1005: ',' expected. email: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.email]),
src/app/login-page/login-page.component.ts:19:42 - error TS1005: ',' expected. password: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.minLength(minLength: 6)])
src/app/login-page/login-page.component.ts:19:65 - error TS1005: ',' expected. password: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.minLength(minLength: 6)])
src/app/login-page/login-page.component.ts:19:119 - error TS1005: ',' expected. password: new FormControl(formState: null, validatorOrOpts: [Validators.required, Validators.minLength(minLength: 6)])
Angular CLI:10.2.0
节点:14.11.0
OS:darwin x64根据问题和代码,这个答案也是正确的不带任何构造函数
import {Component, OnInit} from '@angular/core'
import {FormGroup, FormControl, Validators} from '@angular/forms'
进口
form: FormGroup
ngOnInit() {
this.form = new FormGroup({
email: new FormControl(null, [Validators.required, Validators.email]),
password: new FormControl(null, [Validators.required, Validators.minLength(6)])
})
}
Code您可以使用
FormBuilder
来帮助完成此操作
实施步骤
- 注入
FormBuilder
构造函数(私有fb:FormBuilder){}
- 调用注入服务上的
函数以生成.group()
。这样,您就不必使用表单组
,一切正常new
新表单组(控件:{…
似乎不是有效的语法。@AndreiGătej我从Udemy couse编写代码,但它是Angular.import的旧版本,{FormGroup,FormBuilder,Validators}从'@Angular/forms'
ngOnInit() {
this.form = this.fb.group({
email: [null, [Validators.required, Validators.email]],
password: [null, [Validators.required, Validators.minLength(6)]]
})
}