Here is my function, where I need to add properties as disabed
and value
how to do that? also validation
should be added if requried.
formBuilder(form, props) {
let { required, disabled, value } = props;
const formControl = new FormControl();//how to add?
if (required) {
formControl.setValidators([
Validators.required,
this.validate.plainText,
]);
}
form.addControl(props.controlName, formControl);
}
getting props as:
{
"controlName": "userName",
"validateType": "plainText",
"elementType": "text",
"placeHolder": "User Name 0",
"value": "sample",
"required": false,
"disabled": true,
"errors": {
"required": "User Name must required"
}
}
CodePudding user response:
Like this :
formBuilder(form, props) {
const { required, disabled, value } = props;
const validators = [this.validate.plainText];
if (required) validators.push(Validators.required);
const formControl = new FormControl({ value, disabled }, validators);
form.addControl(props.controlName, formControl);
}
CodePudding user response:
Try this.
formBuilder(form, props) {
let { required, disabled, value } = props;
const formControl = new FormControl(value);//how to add?
if (required) {
formControl.setValidators([
Validators.required,
this.validate.plainText,
]);
}
if (disabled) {
formcontrol.disable();
}
form.addControl(props.controlName, formControl);
}
CodePudding user response:
The FormControl constructor is heavily overloaded.
https://angular.io/api/forms/FormControl#constructor
There are 2 non-deprecated signatures, each with union types
new <T = any>(
value: T | FormControlState<T>,
opts: FormControlOptions & { nonNullable: true; }
): FormControl<T>
new <T = any>(
value: T | FormControlState<T>,
validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[],
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
): FormControl<T | null>
From here you can use typescript to work out what you can supply in the constructor.
Examples:
const formControl = new FormControl(null) // 2nd signature
const formControl = new FormControl(val) // 2nd signature, implicitly typed
// 2nd signature, implicitly typed, required
const formControl = new FormControl(val, Validators.required)
// 2nd signature, explictly typed
const formControl = new FormControl<IMyInterface>(val)
// 1st signature, explictly typed, not nullable
const formControl = new FormControl<IMyInterface>(val, { nonNullable: true })
// 1st signature, explictly typed, not nullable, required
const formControl = new FormControl<IMyInterface>(val,
{
nonNullable: true,
validators: Validators.required
}
)
// 1st signature, explictly typed, not nullable, disabled
const formControl = new FormControl<IMyInterface>(
{ value: val, disabled: true },
{ nonNullable: true }
)