如何动态创建输入并避免使用表单生成器数组来创建每个控件

时间:2018-03-14 14:50:03

标签: angular ionic-framework

我正在使用Ionic 3.9和Angular 5创建一个评分系统,允许人们搜索列表并使用星形系统来选择成绩(1-5)。然而,他们可以评定超过100种不同类型的东西,他们永远不会对所有这些东西进行评分。

通常我只是使用表单构建器来创建一组输入,但这次我有超过100个,这将花费太长时间来进行硬编码,这将使将来很难添加/删除某些项目。我怎么能避免这个?

我需要将值提交到数据库,密钥为short,值为grade,如

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

示例数组

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>

1 个答案:

答案 0 :(得分:1)

以下是一个例子:

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