i have form component,
@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); } }
from snippet, known code violating dry, repetitions form fields! possible further dryup code minimise repetitions?
thanks.
you can try this:
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] }); }
Comments
Post a Comment