How to avoid code duplication in Angular 2 forms?

All my reactive forms usually include properties and methods:

@Input() public form: FormGroup; public messages = VALIDATION_MESSAGES; @Output() public onFormSubmit: EventEmitter<any> = new EventEmitter(); @Input() public formData; @Input() public controlsConfig: any; protected abstract fb: FormBuilder; isValidControl(controlName: string): boolean { const control = this.form.controls[controlName]; return control.valid || control.pristine; } onSubmit(): void { const form = this.form; if(form.valid) { this.onFormSubmit.emit(form.value); } } 

I selected them in an abstract class

 export abstract class BaseReactiveForm {..} 

And inherit

 @Component({ selector: 'app-login-form', templateUrl: './login-form.component.html', styleUrls: ['./login-form.component.css'] }) export class LoginFormComponent extends BaseReactiveForm implements OnInit { constructor(protected fb: FormBuilder) { super(); } ...} 

Is this decision right?

How to do the right thing? What are the forms of practice?

+5
source share
1 answer

I did the same in my projects, created a base class for processing reactive forms. I think that everything is in order, we should use OOP to simplify this kind of thing. I read somewhere that they will change this part of the frame, because it is repeated, verbose!

Here is my Impl:

 import { FormGroup } from '@angular/forms'; export interface ValidatableFormComponent { formGroup: FormGroup; formErrors: any; validationMessages: any; onValueChanged(data?: any): void; buildForm(): void; onSubmit($event): void; } import { FormGroup, FormBuilder } from '@angular/forms'; import { ValidatableFormComponent } from './validatable-form.component'; export class FormBaseComponent implements ValidatableFormComponent { formGroup: FormGroup; formErrors: any; validationMessages: any; constructor(protected fb: FormBuilder) { } buildForm(): void { this.formGroup.valueChanges .subscribe(data => this.onValueChanged(data)); this.onValueChanged(); } onSubmit($event): void { $event.preventDefault(); } onValueChanged(data?: any): void { if (!this.formGroup) { return; } const form = this.formGroup; for (const field in this.formErrors) { if (this.formErrors.hasOwnProperty(field)) { this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { if (control.errors.hasOwnProperty(key)) { this.formErrors[field] += messages[key] + ' '; } } } } } } isValid(): boolean { return this.formGroup.valid; } } 
+3
source

Source: https://habr.com/ru/post/1263211/


All Articles