如何使用 Angular 在 ngOnInit() 中设置 FormGroup 和 FormControl?

How to set FormGroup and FormControl at the ngOnInit() with Angular?

我刚开始学习Angular,旧版本应该可以:

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: 达尔文 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)])
    })
  }

代码

您可以使用 FormBuilder 来帮助解决这个问题

实施步骤

  • 注入FormBuilder
constructor (private fb: FormBuilder) {}
  • 在注入的服务上调用 .group() 函数以生成 FormGroup。这样你就不必使用 new 一切正常
ngOnInit() {
  this.form = this.fb.group({
    email: [null, [Validators.required, Validators.email]],
    password: [null, [Validators.required, Validators.minLength(6)]]
  })
}

See sample demo