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

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

问题描述

请帮助!!我发现很难编辑表格.我使用反应式表单并将数据添加到表单中并发送到数据库,效果很好.现在,我想查询数据库中的数据,以便可以对其进行编辑并再次发送.数据以json对象的形式从数据库中获取,我尝试将其分配给表单Group变量,这样我就可以在表单中显示数据并发送它,但是会出错.

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.

我还尝试使用模板驱动的表单显示数据.它可以处理输入字段中的值,但是每当我尝试使用ngModel绑定数据时,输入字段中的值都将变为空白.由于这些值是从数据库中获取的.

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(){

   }

}

推荐答案

乌南,我喜欢具有创建表单的功能.是否将数据"作为参数传递给此函数.当您要创建从数组"时,调用一个函数,该函数返回FormGroup []并具有一个数组作为参数.最简单的方法是返回数组转换".因此,我们使用return myArray.map(x => ...)表示与数组的每个元素一起形成一个FormGroup.

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函数必须是"like"-在构造函数中,我有构造函数(私有fb:FormBuilder)-

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天全站免登陆