Editing a Form in Angular

泪湿孤枕 提交于 2019-12-11 22:57:25

问题


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

   }

}

回答1:


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:""})]
  }


来源:https://stackoverflow.com/questions/49596747/editing-a-form-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!