I found out binding input fields name to integer values are not a good practice, but I don't know how else I can do this.
I have to generate dynamic input fields to submit user's medical test results. To associate these inputs with the test ids, I have put the key of the inputs as the ids of the test table.
my current database design
Test Data
| id | test_id | test_data |
|----|---------|-----------|
| 1 | 1 | aaa |
| 2 | 1 | bbb |
Test Results
| id | client_test_id | test_data_id | result |
|----|----------------|--------------|--------|
| 1 | 1 | 1 | 120 |
| 2 | 1 | 2 | 230 |
How I currently generate my Input fields to submit Test results
In component
getTestData(testDatas: any) {
this.clientTestDataNew = [];
testDatas.forEach(testData => {
let testDataItem = new TextTestDataItem({
key: testData.id,
label: testData.name,
type: 'text',
value: '',
required: true,
order: 1
});
this.clientTestDataNew.push(testDataItem);
});
}
In Template
<form *ngIf="clientTestDataNew?.length > 0" (ngSubmit)="onSubmit()" [formGroup]="form">
<div *ngFor="let clientTestDataItem of clientTestDataNew" class="form-row">
<div [formGroup]="form">
<label [attr.for]="clientTestDataItem.key">{{clientTestDataItem.label}}</label>
<div [ngSwitch]="clientTestDataItem.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="clientTestDataItem.key"
[id]="clientTestDataItem.key" [type]="clientTestDataItem.type">
<select [id]="clientTestDataItem.key" *ngSwitchCase="'dropdown'"
[formControlName]="clientTestDataItem.key">
<option *ngFor="let opt of clientTestDataItem.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
<div class="errorMessage" *ngIf="!isValid">{{clientTestDataItem.label}} is required</div>
</div>
</div>
</form>