#angular #angular-reactive-forms
Вопрос:
Я пытаюсь создать динамический макет формы с помощью Angular. Мне нужно загрузить форму из этой полезной нагрузки:
[{
name: 'inputInstallment',
id: '3',
companyId: 1,
dropoffId: 2,
dropoffSectionId: 1,
priority: 2,
type: {
id: '2',
companyId: 1,
description: 'Input text',
__typename: 'DropoffQuestionType',
},
description: 'InputLabel',
answers: [],
options: [],
__typename: 'DropoffQuestion',
}]
Следующий шаг — создание формы.
constructor(
private _abandonmentService: AbandonmentService,
private _router: Router,
private _formBuilder: FormBuilder
) {}
form: FormGroup = this._formBuilder.group({});
createForm(questions: IDropoffQuestion[]) {
for (const question of questions) {
const validatorsToAdd = [];
if (question.required) {
validatorsToAdd.push(Validators.requiredTrue);
}
this.form.addControl(
question.name,
this._formBuilder.control('', validatorsToAdd)
);
}
}
В HTML-файле:
<ng-container
*ngFor="let question of dropoffQuizzData.sections[0].questions"
>
<ng-container
*ngIf="['Input text'].includes(question.type.description)"
>
<acp-form-field>
<acp-input
(acpChange)="
setQuestionValue($event, question.id, question.name)
"
placeholder="{{ question.description }}"
[formControlName]="question.name"
[name]="question.name"
[value]="question.value"
></acp-input>
<acp-hint
type="feedback"
*ngIf="
form.controls[question.name].invalid amp;amp;
(form.controls[question.name].dirty ||
form.controls[question.name].touched)
"
>{{ question.hintMessage }}</acp-hint
>
</acp-form-field>
</ng-container>
</ng-container>
When I send the form for validation, even after filling it out, the answer always returns false
, as if the form was not filled out.
validation method:
checkValidationsForm(formGroup: FormGroup | FormArray) {
Object.keys(formGroup.controls).forEach((field) => {
const control = formGroup.get(field);
control?.markAsDirty();
control?.markAsTouched();
console.log(control?.errors, field);
if (control instanceof FormGroup || control instanceof FormArray) {
this.checkValidationsForm(control);
}
});
}
Am I doing something wrong?