2016-08-01 74 views
1

我有一個表格組件,如何DRYup Angular 2表單組件?

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

從片段中,已知代碼違反幹,有重複的幾乎所有表單字段!是否有可能進一步幹這個代碼來減少重複?

謝謝。

回答

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