Created
August 2, 2023 13:17
-
-
Save RazorNd/3fa5568cfd77b6ac3b21605438ea9384 to your computer and use it in GitHub Desktop.
Упрощение кода работы с реактивными формами
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from '@angular/core'; | |
import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms"; | |
@Component({ | |
selector: 'app-reactive-form', | |
templateUrl: './reactive-form.component.html', | |
styleUrls: ['./reactive-form.component.scss'] | |
}) | |
export class ReactiveFormComponent { | |
genders = ['male', 'female', 'other'] | |
hobbies = new FormArray<FormControl<string | null>>([]) | |
signUpForm = new FormGroup({ | |
'userData': new FormGroup({ | |
'username': new FormControl(null, Validators.required), | |
'email': new FormControl(null, [Validators.required, Validators.email]) | |
}), | |
'gender': new FormControl('female'), | |
'hobbies': this.hobbies | |
}) | |
get hobbyControls(): Array<FormControl<string | null>> { | |
return this.hobbies.controls | |
} | |
onSubmit() { | |
console.log(this.signUpForm) | |
} | |
onValidation(path: string): boolean { | |
return (!this.signUpForm.get(path)?.valid && this.signUpForm.get(path)?.touched) ?? true | |
} | |
onAddHobby() { | |
this.hobbies.push(new FormControl('', [Validators.required])) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment