ghan
ghan

Reputation: 565

How to dynamically create inputs and avoid using a form builder array to create each control

I am using Ionic 3.9 and Angular 5 to create a grading system that will allow people to search a list and use a star system to select a grade (1-5). However there are over 100 different types of things they can grade for and they will never grade all of them.

Usually I just use form builder to create a group of inputs but this time I have over 100 which would just take too long to hardcode and it would make it difficult in the future to add/remove certain items. How can I avoid this?

I need to submit the values to the database with the key being short and the value being grade like

{
    RP: 5, 
    FP: 5, 
    .....
 }

Sample array

this.grades = [
    {id: 0, name: 'Parallel Park', short: 'PP', grade: -1},
    {id: 1, name: 'Reverse Park', short: 'RP', grade: -1},
    {id: 2, name: 'Forward Park', short: 'FP', grade: -1},
];

html

<form name="gradeForm">
  <ion-list>
    <ion-item *ngFor="let grade of grades">
      <h4>{{grade.name}} <a class="float-right" (click)="grade.grade = -1">Reset</a>
      </h4>
      <span>
        <ng-container *ngIf="grade.grade >= 0; else gradeZero">{{grade.short}}-{{grade.grade}}</ng-container>
        <ng-template #gradeZero>{{grade.short}}-0</ng-template>
        <rating
          class="float-right rating"
          [(ngModel)]="grade.grade"
          readOnly="false"
          max="5"
          emptyStarIconName="star-outline"
          starIconName="star"
          nullable="false"
          (ngModelChange)="onRatingChange($event)">
        </rating>
      </span>
    </ion-item>
  </ion-list>
</form>

Upvotes: 0

Views: 102

Answers (1)

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

Here is an example:

form: FormGroup;

grades = [
  {id: 0, name: 'Parallel Park', short: 'PP', grade: -1},
  {id: 1, name: 'Reverse Park', short: 'RP', grade: -1},
  {id: 2, name: 'Forward Park', short: 'FP', grade: -1},
];

ngOnInit(){
  this.toFormGroup();
}

toFormGroup() {
let group: any = {};

this.grades.forEach(grade => {
  group[grade.short] = new FormControl(grade.grade, Validators.required);
});
  this.form = new FormGroup(group);
}

html:

<form (ngSubmit)="onSubmit(form.value)" [formGroup]="form">  
  <div *ngFor="let grade of grades" class="form-row">
    <input type="number" [formControlName]="grade.short"/>
  </div>
  <button type="submit">Submit</button>
</form>

DEMO

Upvotes: 1

Related Questions