我正在尝试组织我的项目并使用表单组合使组件看起来很混乱我想知道是否有办法将表单构建器放在不同的类中并在主要组件中调用它。
我使用了Reactive Form
我试图避免所有的声明
谢谢
构造函数(私有http:Http,private _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 :(得分: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)]]
});
}
}
答案 1 :(得分: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]
});
}