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

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

这个决定是真的吗?

如何做正确的事?有哪些实践形式?

最佳答案

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

这是我的实现:

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

关于oop - 如何避免 Angular 2 表单中的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809997/

相关文章:

oop - 我可以(应该)继承 R 中函数的一部分吗?

java - 扫描仪再次出现问题

java - 哪种设计模式最适合根据某些条件定义多个数据转换器?

Angular2嵌套模板驱动形式

angular - 如何从Visual Studio Code中使用Electron和Angular调试应用程序?

angular - 我正在使用 Chart.js 并希望更改工具提示以根据时间戳输入显示日期格式

c++ - 如何在另一个对象中引用一个对象

php - 将 SQL 查询的结果输出到 PHP 数组

angular - Angular&Electron-IPC通信和服务方法调用

Angular2 路由器链接不工作