我如何DRYup Angular 2表单组件?

时间:2016-08-01 16:23:06

标签: angular coding-style dry code-formatting

我有一个表单组件

@Component({
    templateUrl: '/app/contact/contact.component.html',
    styleUrls: ['app/contact/contact.css'],
    directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES],
    providers: [FormBuilder]
})

export class ContactComponent {

  contactForm: FormGroup;

  subjets = ['Informations', "Offre d'Emploi"];

  name: AbstractControl;
  email: AbstractControl;
  message: AbstractControl;
  subjet: AbstractControl;
  comment: AbstractControl;

  constructor(fb: FormBuilder) {

    this.contactForm = fb.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(2)])],
      'email': ['', Validators.compose([Validators.required, Validators.minLength(2)])],
      'subjet': ['', Validators.compose([Validators.required, Validators.minLength(2)])],
      'comment': ['', Validators.compose([Validators.required, Validators.minLength(20)])]
    });
    this.name = this.contactForm.controls['name'];
    this.email = this.contactForm.controls['email'];
    this.subjet = this.contactForm.controls['subjet'];
    this.comment = this.contactForm.controls['comment'];
  }

    onSubmit(form: any): void {
    console.log('Valeurs du formulaire:', form);
  }
}
从代码片段中可以看出,代码违反了DRY,几乎所有表单字段都重复了!是否可以进一步DRYup此代码以最小化重复?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

constructor(fb: FormBuilder) {
  let group = {};

  const fields = [
    { key: 'name', len: 2 }, 
    { key: 'email', len: 2 }, 
    { key: 'subjet', len: 2 }, 
    { key: 'comment', len: 20 }];

  fields.forEach(field => {
    group[field.key] = ['', 
       Validators.compose([Validators.required, Validators.minLength(field.len)])];
  });

  this.contactForm = fb.group(group);

  fields.forEach(field => {
    this[field.key] = this.contactForm.controls[field.key]
  });
}