Angular:json 到 formBuilder 到 json

2024-01-12

我从我的服务器收到一个包含问题和不同选项的 json:

[
{"description":"what is a color","questionID":"1","options":[{"response":"blue","optionID":"1"},{"response":"red","optionID":"2"},{"response":"football","optionID":"3"}]},
{"description":"what is a sport","questionID":"2","options":[{"response":"working","optionID":"4"},{"response":"playing","optionID":"5"},{"response":"dad","optionID":"6"},{"response":"chess","optionID":"7"}]}
]

使用表单构建器,我为此创建了一个表单:

如果我按提交,我想将此 json 发送到我的服务器:

{
"answers": [{"questionID":"1", "selectedoptionIDS":[{"selectedOptionID":"2"}]},
{"questionID":"2", "selectedoptionIDS":[{"selectedOptionID":"1"},{"selectedOptionID":"3"}]}
],
"email": "[email protected] /cdn-cgi/l/email-protection"
}

我知道如何使用 formbuilder 构建表单,但是当我按下提交时,我在响应正确的 JSON 时遇到了麻烦。当然是因为我无法使用此复选框。有人可以帮我解决这个问题吗?

网页

  <form [formGroup]="examForm" (ngSubmit)="onSubmit(examForm.value)">
    <div formArrayName="answers">
      <div *ngFor="let question of questions; let i=index">
        <label>{{i+1}}) {{question.description}}</label>
        <br />
        <div *ngFor="let response of question.options">
          <input type="checkbox" value="response.optionID" />
          {{response.response}}
        </div>
      </div>
    </div>
    <label>Email:</label>
    <input class="form-control" id="email" type="text" formControlName="email">
    <div class="block-content block-content-full block-content-sm bg-body-light font-size-sm">
      <button class="btn btn-primary" type="submit">Submit</button>
    </div>
  </form>

TS Page

import { Component, OnInit } from '@angular/core';
import { ExamSimulatorService } from '../services/exam-simulator.service';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'app-exam',
  templateUrl: './exam.component.html'
})
export class ExamComponent implements OnInit {

  software;
  questions;
  examForm;


  constructor(
    private examSimulatorService: ExamSimulatorService,
    private formBuilder: FormBuilder
  ) {
    this.examForm = this.formBuilder.group({
      email: "",
      answers: this.formBuilder.array([
        this.initAnswer()])
    })


  }
  buildForm() {
    for (var i = 0; i < this.questions.length() + 1; i++) {
      this.addAnswer();
    }
  }
  initAnswer() {
    return this.formBuilder.group({
      questionID: "",
      selectedOptionIDs: this.formBuilder.array([
        this.initOptions()
      ])
    })
  }
  initOptions() {
    return this.formBuilder.group({
      selectedOptionID: ""
    })
  }
  addAnswer() {
    const answers = <FormArray>this.examForm["controls"]["answers"];
    answers.push(this.initAnswer())
    console.log(this.examForm);
  }

  addOption(i) {
    const options = <FormArray>this.examForm["controls"]["answers"]["controls"][i]["controls"]["selectedOptionIDs"]
    options.push(this.initOptions())
  }

  ngOnInit() {
    this.activatedRoute.paramMap
      .subscribe(params => {
        this.software = params['params']['software'];
        this.examSimulatorService.getExam(this.software).subscribe(response =>
          this.questions = response["questions"]["questionList"]);

      })
    setTimeout(() => this.buildForm(), 200)


  }
  onSubmit(values) {
    //this.examSimulatorService.addQuestion(values).subscribe(
    //  (responses) => {
    //    console.log(responses);
    //  });
    //this.options.clear();
    console.log(values);
  }

}

您可以使用响应式表单的完整帮助,而不是使用您自己的模型。最终模型并不完全是您所需要的,但您可以从中找到解决方法。您可以在此处查看工作示例https://stackblitz.com/edit/angular-1gtfmf https://stackblitz.com/edit/angular-1gtfmf

成分

export class ExamComponent implements OnInit {
  @Input() name: string;
  questionsList;
  examForm: FormGroup;
  dataModel: any; //active model

  constructor(
    private examSimulatorService: QuestionService,
    private formBuilder: FormBuilder
  ) { }

  get question(): FormGroup {
    return this.formBuilder.group(
      {
        questionID: "",
        description: "",
        options: this.formBuilder.array([])
      }
    );
  }

  get option(): FormGroup {
    return this.formBuilder.group({
      optionID: "",
      response: "",
      selected: false
    });
  }

  ngOnInit() {

    this.dataModel = Object.create(null);

    this.examForm = this.formBuilder.group({
      email: ['', [Validators.required]],
      questions: this.formBuilder.array([])
    });

    this.examSimulatorService.getAllQuestion().subscribe(response => {
      this.questionsList = response.data;
      this.loadForm(this.questionsList);
      console.log(this.questionsList);
    });

    this.examForm.valueChanges.subscribe(data => {
      this.dataModel = data;
    });
  }

  loadForm(data) {

    for (let ques = 0; ques < data.length; ques++) {
      const questionsFormArray = this.examForm.get("questions") as FormArray;
      questionsFormArray.push(this.question);

      for (let opt = 0; opt < data[ques].options.length; opt++) {
        const optionsFormsArray = questionsFormArray.at(ques).get("options") as FormArray;
        optionsFormsArray.push(this.option);
      }
    }

    this.examForm.controls.questions.patchValue(data);
  }

  showSavedValue() {
    return this.dataModel;
  }

  showValue() {
    return this.examForm.getRawValue();
  }

  onSubmit(values) {
    console.log(values);
  }


}

Html

<form [formGroup]="examForm" (ngSubmit)="onSubmit(examForm.value)">

    <div>
        <label>Email:</label>
        <input class="form-control" id="email" type="text" formControlName="email">
    </div>

    <div formArrayName="questions">
        <div *ngFor="let question of examForm.get('questions').controls;let questionIndex=index" [formGroupName]="questionIndex">
            <label>{{questionIndex+1}} </label> {{examForm.value.questions[questionIndex].description}}
            <div formArrayName="options">
                <div *ngFor="let option of question.get('options').controls; let optionIndex=index" [formGroupName]="optionIndex">
                    <input type="checkbox" formControlName="selected" value="" /> {{examForm.value.questions[questionIndex].options[optionIndex].response}}
                </div>
            </div>
        </div>

        <div class="block-content block-content-full block-content-sm bg-body-light font-size-sm">
            <button class="btn btn-primary" type="submit">Submit</button>
        </div>
    </div>
</form>

<pre>  {{showSavedValue() | json }}

<pre>{{showValue() | json}}</pre>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular:json 到 formBuilder 到 json 的相关文章

  • Angular SlickGrid 对齐标题文本

    我正在使用角度SlickGrid并希望将列标题中的文本居中或右对齐 并非所有列都以相同的方式 我发现 有一个headerCssClass列定义中的属性 但我一直尝试 这种样式似乎从未被应用 对于列定义 id sourceNumber nam
  • 参考上一个问题:为什么 VBA 没有加载所有发票详细信息

    除了上一个问题之外 我们在销售发票上仍然存在相同的加载失败问题 下面的 VBA Json 仍然仅加载一行或第一个产品详细信息行 而不是与表中该销售发票合作的所有产品行详细信息 我们希望下面的 VBA 能够根据参数加载发票详细信息 例如 如果
  • 后退按钮 (Chrome) 在 Play Framework 中获取 Json 而不是 HTML

    各位 我有一个 Web 应用程序 我在其中对同一资源的 JSON 和 HTML 表示重复使用了相同的路由 现在我们将其称为 foo details 该页面是从 bar details 链接的 因此 查看 bar details 您会看到链接
  • 如何让 webpack 和 iis express 协同工作?

    I have Angular 2 和 Webpack 2 入门 https github com qdouble angular webpack2 starter它通过 webpack dev server 在节点上运行 我如何使用 web
  • 使用 System.Text.Json 序列化记录成员

    我在记录中使用自我引用成员 如下所示 type Payload Id Guid member x DerivedProperty Derived Property using id x Id NewtonSoft Json会序列化这个 但是
  • 找不到管道“货币”(AOT)

    我们有一个从 Angular 6 升级到 7 的 Angular 我们正在使用内置的currency管道 服务时一切正常 ng serve 以及在 DEV 中构建时 但是当我们尝试构建生产我们正在得到The pipe currency co
  • 有没有办法扩展 angular.json 中的配置?

    在构建 Angular 6 应用程序时 我需要同时指定两件事 如果是生产或开发版本 我正在使用的区域设置 In my angular json I have build configurations production fileRepla
  • 我可以将 JSON 字符串转换为 JsonResult 吗?

    我在数据库中存储了一些存储的 JSON 字符串 我想将其作为 JsonResult 返回给客户端 我知道 Json object 将对象转换为 JsonResult 但如果我已经将结果存储在字符串中怎么办 我可以将其转换为 JsonResu
  • 将 Json 数据返回给 Ajax 调用

    我在 MVC 中有一个方法 我将其发布到它 并且我需要返回一些数据以进行处理 这是我发布到的 MVC 方法 返回值是 json 数据 HttpPost public JsonResult GetCalculateAmortizationSc
  • 在Python中,如何通过去掉括号和大括号来打印Json

    我想以一种很好的方式打印 Json 我想去掉方括号 引号和大括号 只使用缩进和行尾来显示 json 的结构 例如 如果我有一个像这样的 Json A A1 1 A2 2 B B1 B11 B111 1 B112 2 B12 B121 1
  • 解码Json数据数组并插入到mysql

    这个问题可能已经在这里问过 但我尝试搜索找不到它 我有如下 Json 数据 CityInfo CityCode 5599 Name DRUSKININKAI CityCode 2003 Name KAUNAS CityCode 2573 N
  • 如何绕过 CF8 编码不可打印字符中的 SerializeJSON?

    SerializeJSON 创建具有不可打印字符 即 ASCII 21 的 JSON 这是无效的 JSON 我该如何解决这个问题 删除不可打印字符的正则表达式会起作用吗 什么正则表达式会删除不可打印的字符 嗯 这个简单的解决方案是为 cff
  • 具有多个 Angular 2 应用程序的 ASP.Net Core MVC [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我正在尝试为一个我知道会变得越来越复杂的项目准备结构 我想使用 ASP Net Core MVC 进行顶层导航 我想在每个主视图中放置
  • PySpark - RDD 到 JSON

    我有一个 Hive 查询返回以下格式的数据 ip category score 1 2 3 4 X 5 10 10 10 10 A 2 1 2 3 4 Y 2 12 12 12 12 G 10 1 2 3 4 Z 9 10 10 10 10
  • 将 JSON 发送到 Spring MVC 控制器

    我正在尝试将 JSON 发送到 Spring MVC 控制器 在 Spring MVC 方面 一切都配置正确 下面是代码 但似乎没有运行
  • 反序列化动态 JSON 文件 C# NewtonSoft.JSON

    正在反序列化一个动态 JSON 文件 该文件可能包含 2 个单独的类 我不知道数组中将包含哪种类型的数据 问题是 我将根对象反序列化为 Base 类型 subtests 对象被反序列化为 Subtest 但 subtests 数组可能是 B
  • 如何在全局配置文件中配置 ngx-logger 的记录器级别

    我最近包括了ngx logger对于我在应用程序中实现记录器级别的项目 我已将记录器级别硬编码为app module ts在配置内ngx logger但我需要在一些全局配置文件中实现这一点 我遵循了教程here https medium c
  • Angular 12将json导入到ts中

    我有一个 json 文件src assets version json包含以下内容 VERSION 1 0 0 然后我将文件导入到 ts eg import as VersionInfo from src assets version js
  • Rspec 控制器测试,传递 JSON 参数

    我试图实现以下目标 在 RSpec 控制器测试中创建 POST json 请求 并向其传递参数 这是我的代码 it returns access token do post login email bla password bla1 for
  • Angular AWS Amplify 验证器额外字段

    我正在尝试将 AWS Amplify 与 Angular 结合使用 通过 Cognito 进行身份验证 我面临的问题是 当我调用该组件时

随机推荐

  • 如何在活动中创建覆盖视图

    我有一个要求 我有一个活动显示 Facebook feed 等项目列表 当单击其中一个列表项中的按钮时 必须弹出一个对话框 其中将显示该项目的评论 我正在查看文档并发现我们必须创建一个对话框片段 http developer android
  • 代码点火器文件上传

    我正在执行以下操作来使用 codeigniter 上传文件 图像 我想要做的是修改错误消息 以便明显地看出错误与哪个字段相关 因为页面上有多个上传选项 下面是我的上传代码 config upload path media uploads u
  • Android 从剪贴板管理器复制/粘贴

    是否可以发送过去的命令 以便将文本粘贴到当前聚焦的编辑文本中 设想 后台服务监听通知 完成 收到通知后 需要将文本复制到剪贴板 完成 将文本粘贴到任何当前聚焦的字段 如果不可能 则放弃粘贴命令 我知道如何复制文本ClipboardManag
  • 在 Firebase 数据库规则上创建自定义验证

    我想使用 firebase 实时数据库创建一个聊天应用程序 我已经拥有自己的服务器以及我自己的用户和收件人身份验证 所以基本上我想做的是 我希望我的服务器能够生成房间及其房间密钥 因此仅向我共享密钥的人可以访问房间 进行读写 也许流程是这样
  • 更快(最快?)的方法来获取包含超过 200,000 个文件的目录中的文件数

    我有一些包含测试数据的目录 通常每个目录有超过 200 000 个小 4k 文件 我使用以下 C 代码来获取目录中的文件数 int fileCount System IO Directory GetFiles C SomeDirectory
  • 在 Python 中传递带有空格的命令行参数

    我试图传递带有空格的命令行参数 但是sys argv 1 strip 只给我论点的第一个词 import sys os docname sys argv 1 strip e g python myscript py argument wit
  • 我如何获取本地变更列表并将其发送给 Perforce 中的其他人?

    我如何获取本地变更列表并将其发送给 Perforce 中的其他人 更具体地说 我想将未提交的更改从本地待定更改列表发送到另一个用户的待定更改列表 set P4DIFF C cygwin bin diff exe p4 diff du c 1
  • 无法下载 CentOs 8 的 RemiRepo

    当我尝试安装 Remi 存储库来下载 php 时 我遇到了麻烦 当我使用命令时 dnf install https rpms remirepo net enterprise remi release 8 rpm 我有一个错误 Error P
  • 关闭 Chrome 中的 Silverlight 插件警告

    我正在使用 Silverlight 3 应用程序并使用 Chrome 作为我的测试浏览器 在调试时 我不断收到弹出消息 插件无响应 以下插件无响应 未知 你想阻止我吗 Yes No 如何在 Chrome 中关闭此功能 VS可以设置为只在调试
  • 使用 next-redux-wrapper 时访问 React 外部的 Redux 存储

    我有一个 NextJS React 应用程序 它使用 next react wrapper 基本上是一个 HOC app tsx像这样 app tsx import withRedux from next redux wrapper cla
  • 要求 IntelliJ IDEA 将构建的工件安装到 maven 本地存储库中

    标题总结如下 我正在寻找一种方法来构建 jar 文件并将其安装到 IntelliJ IDEA 中我的计算机上的 Maven 本地存储库中 而无需每次都转到命令提示符并发出mvn install install file命令 最重要的是我希望
  • 如果 URL 以“blob:”开头,如何使用 Python 3/Selenium 下载图像?

    使用 web whatsapp de 时 可以看到收到的图像的链接可能如下所示 blob https web whatsapp com 3565e574 b363 4aca 85cd 2d84aa715c39 如果链接被复制到地址窗口 它将
  • 使用 Entity Framework Core 2.1 插入时态表时出错

    尝试使用 Entity Framework Core 2 1 插入时态表时出现以下错误 无法将显式值插入表 db test dbo Department 中的 GENERATED ALWAYS 列 对列列表使用 INSERT 可排除 GEN
  • 允许相同密钥的通用集合

    收藏如HashTable and Dictionary不允许添加具有相同键的值 但我想将具有相同键的相同值存储在Collection
  • FutureProvider 坏了还是什么?

    我尝试这个简单的 FutureProvider 代码 但它给了我一个错误 Error Could not find the correct Provider
  • chrome.identity.launchWebAuthFlow 的正确重定向 URL 是什么?

    我想使用chrome identity http developer chrome com apps app identity htmlChrome 打包应用程序中的 API 允许用户进行身份验证github http developer
  • 变量的命名方式对应用程序的内存使用有影响吗?

    声明变量名时 其名称的长度对应用程序的总内存有多大 如果有的话 影响 无论如何 有最大长度吗 或者我们可以根据需要自由地详细说明我们的变量 和实例 吗 实际上 这取决于语言 如果您使用 C 或 C 则没有影响 如果您使用解释性语言 则可以传
  • 元组的替代方案

    由于 net框架4 0支持元组 Tuple 类在 3 5 中不可用 但是我有什么方法可以在 net 3 5 中创建自己的类 MyTuple 吗 是的 您可以创建自己的元组 这没有什么难的 这是一个例子Tuple
  • 从 R 中的因子变量创建逻辑变量

    我需要从分类 因子 变量创建逻辑变量 True False 我决定使用 dat var dat var in c option1 lt TRUE dat var dat var in c option2 lt FALSE 但我在两行中都收到
  • Angular:json 到 formBuilder 到 json

    我从我的服务器收到一个包含问题和不同选项的 json description what is a color questionID 1 options response blue optionID 1 response red option