I am using reactive forms with Angular4. My form:
this._form = this._formBuilder.group({
id: [''],
name: ['', [Validators.required]],
type: ['', [DropDownValidator.Validate()]],
length: ['', [Validators.required]],
timesPerWeek: ['', [Validators.required]],
workouts: this._formBuilder.array([
this._formBuilder.group({
name: ['', Validators.required],
description: ['', Validators.required]
})
])
});
I am then using generic validation component which uses following function:
// returns false if no error, returns true if error
public IsFieldInvalid(form: FormGroup, field: string, errorType: string){
return form.get(field).hasError(errorType) && form.get(field).dirty;// || form.get(field).hasError(errorType) && form.get(field).pristine && this.IsControlType(form, field, 'radio');
}
In html I then pass form and field via shared component for high level 'name':
<app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'name','required')" errorMsg="Field is required"></app-field-error-display>
As you can see for first name, I have no issue I just pass field name 'name'.
How can I access nested 'name' inside of workouts array for validation to be accepted inside IsFieldInvalid function as 'field:string' parameter? I tried multiple things but with errors.
I tried this with errors:
<app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form,'_form.controls.workouts.controls[i].controls.name','required')" errorMsg="Field is required"></app-field-error-display>
get()
function may receive array of strings or numbers or just a string, which suits your case. Then, _find()
function will just split it using .
(period) delimiter. Your path contains workouts
form array which contains a single form group with index 0, which has form controls name
and description
.
So just try to pass workouts.0.name
for name or workouts.0.description
paths:
<app-field-error-display [displayError]="formValidationService.IsFieldInvalid(_form, 'workouts.0.name', 'required')"
errorMsg="Field is required"></app-field-error-display>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.