Reputation: 2184
I have just started to learn Angular and old version should work:
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() {
}
}
The errors:
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 Node: 14.11.0 OS: darwin x64
Upvotes: 0
Views: 4015
Reputation: 2184
This answer is also correct according to the question and code. Without any constructor.
import {Component, OnInit} from '@angular/core'
import {FormGroup, FormControl, Validators} from '@angular/forms'
Imports
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
Upvotes: 0
Reputation: 15083
You can use FormBuilder
to help with this
FormBuilder
constructor (private fb: FormBuilder) {}
.group()
function on the injected service to generate the FormGroup
. This way you do not have to use new
and everything worksngOnInit() {
this.form = this.fb.group({
email: [null, [Validators.required, Validators.email]],
password: [null, [Validators.required, Validators.minLength(6)]]
})
}
Upvotes: 1