Why is this form control error messages not showing I have an array and I'm reading it and generate dynamically questions. I can't find what is the mistake I have done in this code.
I have to show 4 error messages
- Required
- Min value validate
- Max value validate
- Unique value validate
I have an array which contains a question
questions: any = [{
id: 13,
surveyNo: 5,
qNo: 3,
question: 'Please rank the following features in order of importance,where 1 is the most important to you.?',
qType: 3,
noAnswrs: 4,
answerType: 1,
answers: ['Location', 'Confort', 'Service', 'Value for money']
}];
I generated form controller dynamically likewise,
createForms(): any {
this.surveyQuestionForm = this.fb.group(
this.questions.reduce((group: any, question: { qNo: string; }) => {
return Object.assign(group, { ['q' + question.qNo]: this.buildSubGroup(question) });
}, {})
);
}
private buildSubGroup(question) {
switch (question.qType) {
case 3:
return this.fb.group(
question.answers.reduce((subGroup, answer) => {
return Object.assign(subGroup, { [answer]: ['', [Validators.required, Validators.min(1), Validators.max(3)]] });
}, {}), { validators: [this.uniqueNumbersValidator()] }
);
default:
throw new Error('unhandled question type');
}
}
uniqueNumbersValidator() {
return (ctrl: AbstractControl) => {
const fg = ctrl as FormGroup;
let allUnique = true;
const values = [];
Object.values(fg.controls).forEach(fc => {
const val = fc.value;
if (val && allUnique) {
if (values.includes(val) && allUnique) {
allUnique = false;
}
values.push(val);
}
});
return (allUnique) ? null : { notAllUnique: true };
};
}
Here is my html code
<div class="form-group" formGroupName="{{'q' + question.qNo}}">
<label class="control-label"> {{question.qNo}})
{{question.question}}</label>
<div class="ml-3">
<table>
<tr *ngFor="let anwr of question.answers; let a=index">
<td>{{a+1}}. {{anwr}} </td>
<div class="invalid-feedback"
*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched && surveyQuestionForm.get('q'+ question.qNo).hasError('required')">
Answer required</div>
<div class="invalid-feedback"
*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched && surveyQuestionForm.get('q'+ question.qNo).hasError('max')">
max value</div>
<div class="invalid-feedback"
*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched && surveyQuestionForm.get('q'+ question.qNo).hasError('min')">
min value</div>
<div class="invalid-feedback"
*ngIf="surveyQuestionForm.get('q'+ question.qNo).touched && surveyQuestionForm.get('q'+ question.qNo).hasError('notAllUnique')">
Already inserted value</div>
<td>
<input type="number" style="width:40px;"
id="q{{question.qNo}}_{{a}}"
[ngClass]="{'is-invalid': surveyQuestionForm.get('q'+ question.qNo).errors
&& surveyQuestionForm.get('q'+ question.qNo).touched}"
formControlName="{{anwr}}"
class="text-center" />
</td>
</tr>
</table>
</div>
</div>
Here is stackblitz code https://stackblitz.com/edit/angular-pxdesk
please tell me what is the problem having this.
thanks