2017-07-13 52 views
1


我想組織我的項目和使用窗體groupe使組件看起來messsy我想知道是否有一種方法可以將窗體生成器放在不同的類並在我的主要組件中調用它。
我正在使用Reactive Form。
我試圖避免這一切報關單
謝謝如何把表單放在一個單獨的文件角4

構造(私有HTTP:HTTP,私人_filterService:FiltreAdvancedSearchService){ this.loading = TRUE;

this._filterService.getAllData().subscribe(res => { 
    this.Recherche = res; 
    this.loading = false; 
    this.status = 304; 

}, err => { 
    this.status = err.status; 
    console.log(this.status) 
}); 
this.SearchForm = new FormGroup({ 
    start_date: new FormControl('', [Validators.required ]), 
    end_date: new FormControl('', [Validators.required ]), 
    n_doc: new FormControl('', [ Validators.pattern('^[0-9]+$') ]), 
    pw: new FormControl('', [Validators.pattern('^[0-9]+$') ]), 
    li: new FormControl('', [Validators.pattern('^[0-9]+$') ]), 
    fac: new FormControl('', [Validators.pattern('^[0-9]+$') ]), 
    cont: new FormControl('', [Validators.pattern('/^[a-zA-Z]$/') ]), 
    type: new FormControl(this.types), 
    cat: new FormControl(this.categories), 
    immat: new FormControl(), 
    ser: new FormControl(''), 
    mod: new FormControl(''), 
    en: new FormControl(this.energies), 
    client_num: new FormControl(), 
    client_nom: new FormControl(), 
    reg: new FormControl(), 

}); 

}

+0

發佈您的代碼,以便識別代碼如何優化 – umar

回答

0

是的,它可能把表單生成器例如ngOnInit()函數之外。你可以這樣做:

ngOnInit(){ 
blablabla ... 
this.buildform(); 
} 

buildForm() { 
     this.form = this.fb.group({ 
      Id: [{ value: '', disabled: true }, Validators.required], 
      Insertions: [{ value: '' }, Validators.required], 
      IdForm: [{ value: '', disabled: !this.is_edit }, Validators.required], 
      price: ['', Validators.required] 
     }); 
    } 
+0

謝謝,您剛剛救了我的一天! –

1

用這樣的靜態函數創建一個可注入的服務類。爲單獨的表單添加更多功能。

import {Injectable} from "@angular/core"; 
import {FormBuilder, FormGroup, Validators} from "@angular/forms"; 
@Injectable() 
export class FormHelper { 

    constructor(private fb: FormBuilder) {} 

    buildForm1(entityName: string): boolean { 
    return this.fb.group({ 
     'firstName': [null, [Validators.required]], 
     'secondName': [null, [Validators.minLength(10), Validators.maxLength(2000)]] 
    }); 
    } 
} 
相關問題