Skip to content

Instantly share code, notes, and snippets.

@RazorNd
Created August 2, 2023 13:17
Show Gist options
  • Save RazorNd/3fa5568cfd77b6ac3b21605438ea9384 to your computer and use it in GitHub Desktop.
Save RazorNd/3fa5568cfd77b6ac3b21605438ea9384 to your computer and use it in GitHub Desktop.
Упрощение кода работы с реактивными формами
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