如何避免Angular 2表单中的代码重复?

时间:2017-01-23 15:33:57

标签: oop angular

我的所有反应形式通常包括属性和方法:

  @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);
    }
  }

我在抽象类中选择了它们

export abstract class BaseReactiveForm {..}

继承

@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();
  }
...}

决定是真的吗?

如何做正确的事情?什么是实践形式?

1 个答案:

答案 0 :(得分:3)

我在我的项目上做了同样的事情,创建了一个基类来处理反应形式的东西。我认为没关系,我们应该使用OOP来简化这种东西。我在某处读到他们会调整框架的这一部分,因为它是重复的,冗长的!

这是我的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;
  }
}