加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:24:00 所属栏目:安全 来源:网络整理
导读:我的所有反应形式通常包括属性和方法: @Input() public form: FormGroup; public messages = VALIDATION_MESSAGES; @Output() public onFormSubmit: EventEmitterany = new EventEmitter(); @Input() public formData; @Input() public controlsConfig: any
我的所有反应形式通常包括属性和方法:
@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来简化这种东西.我在某处读到他们会调整框架的这一部分,因为它是重复的,冗长的!

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读