如何设置新的表单控件的动态验证



我有一个对象,应该建立一个窗体

const textBox = {
fontColor: 'red',
fontSize: '20',
placeholder: 'name',
name: 'input name',
label: 'mohamed',
validation: {
required: true
}
};

我创建了一个简单的动态表单,但是我需要为每个表单控件设置验证器

ngOnInit(): void {
const inputDataObj = {} as any;
for (const prop of Object.keys(this.InputObj)) {
debugger;
if (prop !== 'validation') {
inputDataObj[prop] = new FormControl(this.InputObj[prop]);
this.inputProps.push(prop);
}
}
this.form = new FormGroup(inputDataObj);
}

现在我需要设置验证到任何表单控件,验证是一个可选的属性,有些对象可能没有任何验证

我认为只有当validation对象中的required属性设置为true时,您才想添加验证。

如果是这样,您需要首先创建FormControl,然后使用addValidators方法动态添加验证:

import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
const textBoxes = [
{
fontColor: 'red',
fontSize: '20',
placeholder: 'name',
name: 'input name',
label: 'mohamed',
validation: {
required: true,
},
},
];
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
public form = new FormGroup({});
ngOnInit(): void {
for (const textbox of textBoxes) {
const control = new FormControl(textbox.placeholder);
if(textbox.validation.required){
control.addValidators(Validators.required);
}
this.form.addControl(textbox.name, control);
}
}
}

Stacblitz

//你的组件

ngOnInit() {
const textBoxes = [
{
fontColor: 'red',
fontSize: '20',
placeholder: 'name',
name: 'input name',
label: 'mohamed',
validation: [
required: true,
min: 5,
],
},
];
this.createForm(textBoxes);
}    
createForm(controls: YourModel[]) {
this.formGroup = this.service.toFormGroup(controls);
}

//service(如果你把你的功能拆分到一个服务中会更好)

validatorsMap = {
required: () => Validators.required,
min: (num: number) => Validators.min(num),
... etc: etc(),
... etc: etc(),
};

toFormGroup(inputs: YourModel[]): FormGroup {
const group: any = {};
inputs.forEach(input => {
const validations: any[] = this.getValidators(input);
group[input.name] = new FormControl(
'', // initial value
validations// here are that you want!
);
});
return new FormGroup(group);
}
getValidators(input: ControlModel) {
return input.validation
.map(validation => {
return fn = this.validatorsMap[validation.name];
});
}

相关内容

  • 没有找到相关文章

最新更新