typescript 在Angular中绑定多个星星

k2fxgqgv  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(106)

我有这个数组

"rating": [
            {
                "sno": 1,
                "question": 13,
            },
            {
                "sno": 2,
                "question": 5,
            },
            {
                "sno": 3,
                "question": 7,
            },
  ..
  .

从中我将创建一个动态星星
https://valor-software.com/ngx-bootstrap/#/components/rating?tab=overview#rating-basic
对于单星星,我可以创建,但我想多星,如果我提交一份表格
那么表单的响应应该是这样的格式

{
    "answer": {
        "5": 4,
        "7": 3,
        "13": 4
    },
    "comments": "user comments"
}

有办法吗谢谢

eoxn13cs

eoxn13cs1#

以下是按键创建动态表单控件的步骤/概念:
1.为answer控件创建一个FormGroup
1.迭代rating数组并将FormControl(以question为键)添加到answerFormGroup
1.使用*ngForkeyvalue管道生成answerFormGroup的嵌套窗体控件。

ngOnInit() {
  this.form = this.fb.group({
    answer: this.fb.group({}),
    comments: this.fb.control(''),
  });

  for (let rate of this.rate.rating) {
    this.answer.addControl(rate.question.toString(), new FormControl());
  }
}

get answer(): FormGroup {
  return this.form.controls.answer as FormGroup;
}

answerControl(formControl: AbstractControl<any, any>): FormControl {
  return formControl as FormControl;
}
<div formGroupName="answer">
  <ng-container *ngFor="let control of answer.controls | keyvalue">
    <label>Question {{ control.key }}</label>
    <rating [max]="5" [formControl]="answerControl(control.value)"></rating>
    <br />
  </ng-container>
</div>

Demo @ StackBlitz

相关问题