【问题标题】:Editing a Form in Angular在 Angular 中编辑表单
【发布时间】:2018-09-10 19:30:18
【问题描述】:

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

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

<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>

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

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

   }

}

【问题讨论】:

  • 你的问题太模糊了,你到底想达到什么目的,实际结果又是什么?见How do I ask a good question?
  • 我的目标是编辑我发布的那个 html 表单。这些值显示在输入字段中,但是当我添加 ngModel 以获取值时,这些值消失了。如果您可以发布有关如何以角度编辑动态表单的链接或教程,我将不胜感激。谢谢
  • 你试过 this.myform.patchValue(newJsonValueFromDB) 吗? angular.io/api/forms/AbstractControl#patchValue

标签: angular angular-ngmodel angular-reactive-forms angular-forms


【解决方案1】:

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

所以,如果你有“数据”,你可以做

   this.myForm=createForm(data)

如果你没有数据你可以做

   this.myForm=createForm(null)

函数必须是“喜欢”的——在构造函数中我有构造函数(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:""})]
  }

【讨论】:

  • 非常感谢。创建表单功能有效,但获取项目和获取选项似乎不起作用,因为值仍然为空。当我尝试为前缀、文本和值添加 formControlName 时,它​​告诉我找不到表单控件。请问我该如何解决这个问题?谢谢
  • 我在这里找到了解决方案stackoverflow.com/questions/46694787/…
  • @Unah,抱歉耽搁了。我总是像我展示的那样制作数组(使用数组上的地图)。我认为你的数据会有问题。我想像 [{name:'a',description:'b',items:[{prefix:'c',text:'d',QuestionType:'e',options:[{value:'f' }.{value:'g']]}]。无论如何,我喜欢你自己解决了问题:)
猜你喜欢
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 2012-09-28
  • 1970-01-01
相关资源
最近更新 更多