在 Angular 中编辑表单 [英] Editing a Form in Angular

查看:25
本文介绍了在 Angular 中编辑表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮忙!!我发现编辑表单非常困难.我使用反应式表单并将数据添加到表单并发送到数据库工作得很好.现在我想查询数据库中的数据,以便我可以对其进行编辑并再次发送.数据是以 json 对象的形式从数据库中获取的,我尝试将其分配给表单组变量,以便我可以在表单中显示数据并发送它,但出现错误.

我也试过用模板驱动的表单来显示数据.它适用于输入字段中的值,但每当我尝试将数据与 ngModel 绑定时,输入字段中的值都会变为空白.由于这些值是从数据库中获取的.

<h4 class="card-title">编辑问卷</h4><div *ngIf="问卷调查"><form #myForm="ngForm" novalidate (ngSubmit)="onSubmit(text)" ><div *ngFor="让问卷调查项.item;"><div class="form-group"><input type="text" value="{{ item.prefix }}" class="form-control" ngModel>

<div class="form-group"><input type="text" value="{{ item.text }}" class="form-control" ngModel>

<div *ngFor="let option of item.options; "><div *ngIf="option.value !== '' "><div class="form-group"><input type="text" value="{{ option.value }}" class="form-control" ngModel>

<button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">提交</button><!-- </div>--></表单>

请帮忙!!可以编辑表单并以角度发送到数据库.我的编辑问卷组件看起来像这样我正在使用环回从数据库中查询数据

 import { Component, OnInit } from '@angular/core';从@angular/router"导入{ActivatedRoute};从'../../app/shared/sdk/services'导入{ QuestionnaireApi };从@angular/forms"导入 { Validators, FormGroup, FormArray, FormBuilder };@成分({选择器:'app-editquestionnaire',templateUrl: './editquestionnaire.component.html',styleUrls: ['./editquestionnaire.component.scss']})导出类 EditquestionnaireComponent 实现 OnInit {我的表格:表格组;id:字符串;问卷:任何;文字:任何= [];构造函数(私有路由器:ActivatedRoute,私人问卷api: QuestionnaireApi,私人_fb:FormBuilder) { }ngOnInit() {this.router.params.subscribe(params=>{this.id = params.id;});this.myForm = this._fb.group({名称:["", Validators.required],描述:["", Validators.required],项目:this._fb.array([this.initItem(),])});this.questionnaireapi.findById(this.id).subscribe((data)=>{this.questionnaires = 数据;//this.myForm = <FormGroup>this.questionnaires;console.log(this.myForm.value);},(错误)=>{控制台日志(错误);})}初始化项目(){//初始化我们的项目返回 this._fb.group({前缀:["", Validators.required],文本:["", Validators.required],问题类型:["", Validators.required],选项:this._fb.array([this.InitOption(),])});}初始化选项(){返回 this._fb.group({价值: [""]})}提交(){}}

解决方案

Unan,我喜欢有一个创建表单的功能.您是否将数据"作为参数传递给此函数.当你想创建一个 From Array 时,你调用一个函数,它返回一个 FormGroup[] 并有一个数组作为参数.简单的方法是返回数组转换".所以我们使用 return myArray.map(x=>...) 表示数组的每个元素组成一个 FormGroup.

所以,如果你有数据",你可以做

 this.myForm=createForm(data)

如果你没有数据,你可以做

 this.myForm=createForm(null)

Tha 函数必须像"-在构造函数中我有构造函数(私有 fb:FormBuilder)-

 createForm(data:any):FormGroup{返回 this.fb.group({//看,如果是data,name的值就是data.name,否则""名称:[data?data.name:"", Validators.required],//同上描述描述:[data?data.description:"", Validators.required],项目:this.fb.array([this.getItem(data?data.items:null),])});}getItem(items:any[]):FormGroup[]{返回项目?items.map(x=>{返回 this.fb.group({前缀:[x.prefix, Validators.required],文本:[x.text,Validators.required],问题类型:[x.QuestionType, Validators.required],选项:this.fb.array(this.getOptions(x.options))})}):[this.fb.group({前缀:["", Validators.required],文本:["", Validators.required],问题类型:["", Validators.required],选项:this.fb.array([this.fb.group({value:""}])})]}getOptions(options:any):FormGroup[]{返回选项?options.map(x=>{返回 this.fb.group({值:x.value})}):[this.fb.group({value:""})]}

Please help!! I am finding it very difficult to edit a form. I working with reactive form and adding data to the form and sending to the database works very well. Now I want to query the data in the database so I can edit it and send it again. The data is gotten from the database in form of a json object, I have tried to assign it to a form Group variable so I can display the data in the form and send it but I get errors.

I Have also tried displaying the data with the template driven form. It works with the values in the input fields but anytime I try to bind the data with ngModel the values in the input field becomes blank. Since the values are gotten from the database.

<div class="container">
<h4 class="card-title">Edit Questionnaire</h4>
  <div *ngIf="questionnaires"> 
        <form  #myForm="ngForm" novalidate (ngSubmit)="onSubmit(text)" >
                <div *ngFor="let item of questionnaires.item;" > 
                    <div class="form-group">
                        <input type="text" value="{{ item.prefix }}" class="form-control" ngModel>    
                    </div>

                      <div class="form-group">
                          <input type="text" value="{{ item.text }}" class="form-control" ngModel>  
                      </div>

                      <div *ngFor="let option of item.options; ">
                        <div *ngIf="option.value !== '' ">
                            <div class="form-group">
                                <input type="text" value="{{ option.value }}" class="form-control" ngModel>  
                            </div>
                        </div>

                    </div>

                </div>
                <button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>
             <!--  </div> -->
      </form>
</div>

Please help!! It is possible to edit a form and send to the database in angular. My Edit Questionnaire component looks like this I am using loopback to query the data from the database

 import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { QuestionnaireApi } from '../../app/shared/sdk/services';

import { Validators, FormGroup, FormArray, FormBuilder } from '@angular/forms';


@Component({
  selector: 'app-editquestionnaire',
  templateUrl: './editquestionnaire.component.html',
  styleUrls: ['./editquestionnaire.component.scss']
})
export class EditquestionnaireComponent implements OnInit {

   myForm: FormGroup;
   id: string;
   questionnaires: any;
   text: any = [];


  constructor(
    private router: ActivatedRoute,
    private questionnaireapi: QuestionnaireApi,
    private _fb: FormBuilder
  ) { }

  ngOnInit() {
       this.router.params.subscribe(params=>{
            this.id = params.id;
       });

       this.myForm = this._fb.group({
          name: ["", Validators.required],
          description: ["", Validators.required],
          items: this._fb.array([
              this.initItem(),
          ])
      });


     this.questionnaireapi.findById(this.id).subscribe((data)=>{
              this.questionnaires = data;
           //   this.myForm = <FormGroup>this.questionnaires;
              console.log(this.myForm.value);
      },(error)=>{
              console.log(error);
      })
  }



     initItem(){
        // initialize our item
        return this._fb.group({
            prefix: ["", Validators.required],
            text: ["", Validators.required],
            Questiontype: ["", Validators.required],
            options: this._fb.array([
                this.InitOption(),
            ])
        });
    }


    InitOption(){
         return this._fb.group({
             value: [""]
         })
    }

   onSubmit(){

   }

}

解决方案

Unan, I like have a function to create the form. You pass to this function a "data" as argument or not. When you want to create a From Array, you call a function that return a FormGroup[] and has as argument an array. The easy way is return the "array transformed". So we use return myArray.map(x=>...) that say that with each element of the array you form a FormGroup.

So, if you have "data" you can do

   this.myForm=createForm(data)

if you have not data you can do

   this.myForm=createForm(null)

Tha functions must be "like" -in constructor I have constructor(private fb:FormBuilder)-

  createForm(data:any):FormGroup
  {
     return this.fb.group({
         //see, if data, the value of name will be data.name, else ""
         name: [data?data.name:"", Validators.required],
         //idem description
         description: [data?data.description:"", Validators.required],
         items: this.fb.array([
            this.getItem(data?data.items:null),
         ])
      });
  }
  getItem(items:any[]):FormGroup[]
  {
      return items?items.map(x=>
      {
          return this.fb.group({
              prefix: [x.prefix, Validators.required],
              text: [x.text, Validators.required],
              Questiontype: [x.QuestionType, Validators.required],
              options: this.fb.array(this.getOptions(x.options))
             })
      }):[this.fb.group({
              prefix: ["", Validators.required],
              text: ["", Validators.required],
              Questiontype: ["", Validators.required],
              options: this.fb.array([this.fb.group({value:""}])
      })]    
  }
  getOptions(options:any):FormGroup[]
  {
     return options?options.map(x=>{
          return this.fb.group({
             value:x.value
          })
     }):
     [this.fb.group({value:""})]
  }

这篇关于在 Angular 中编辑表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆