繁体   English   中英

以角度形式修补值

[英]Patch the values in angular form

我正在使用角度6进行应用程序,其中我正在使用角度动态形式。

在创建表单并提交时,我已经完成了所有工作,您可以看到正在运行的stackblitzhttps: //stackblitz.com/edit/angular-x4a5b6-hne6fg

仅供参考:此表单具有子元素,将在单击添加按钮后将其打开并附加,并在单击删除按钮时将其最后删除。

我需要的是,我只需要分别在每一行的编辑期间通过服务将值修补到每个输入即可。

假设我将get服务称为,

    this.dynamicFormService.getRest(url,token).subscribe(res => {
        this.form.value = res.data;   //Tried this line but got error (Cannot assign to 'value' because it is a constant or a read-only property)
     })

我正在尝试将值修补为可以在stacblitz中的dynamic-form.ts中看到的形式,

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
}

如果我将表单作为console.log(this.form.value) ,则结果为

template_desc: ""
template_name: ""
template_properties: Array(0)
length: 0
__proto__: Array(0)

并且获取服务结果中的console.log(res.data)给出,

data:
template_obj_id: "123"
template_desc: "New template description"
template_name: "New Template"
template_properties: Array(1)
0:
property_name: "Property name"
property_origin: ["VBM"]
property_required: true
property_type: "Property type"

我只需要绑定来自res.data的数据就可以修补到所有表单输入。

这些是我需要分别修补到所有输入的 ,例如template_name值为 New Template,而template_desc值为 New template description等。

对于template_properties值来说,另一个重要的事情是array将在创建过程中单击“添加”按钮时打开,但是在编辑过程中,它将自动打开,并且template_properties存在行数。

尽管问题的解释有些大,但我所需要的只是一个问题。我需要将来自服务(res.data)的数据分别修补到每个表单元素,并且包括template_properties在内的所有表单元素都必须可见用户可以在其中编辑和提交表单。

res.data的屏幕截图, 在此处输入图片说明

尝试了以下答案,

 this.form.patchValue({
      template_desc: res.data.template_desc,
      template_name:  res.data.template_name,
    });

但是,如果我给template_properties: res.data.template_properties ,则模板属性不会被绑定,而其他两个template name and desc被绑定。

请帮助实现将数据修补到表单元素...

https://stackblitz.com/edit/angular-x4a5b6-xcychx?file=src%2Fapp%2Fdynamic-form.component.html中 ,我将其放置为“值的路径”。

唯一要考虑的是,您需要像添加数组一样将元素添加到表单中。

  //This function serve to add to the array the elments of the arrays
  //Is the same that we use when add a new line to the Array Form
  addControls(control: string) {
    let question: any = this.questions.find(q => q.key == control);
    let children = question ? question.children : null;
    if (children)
      (this.form.get(control) as FormArray).push(this.qcs.toFormGroup(children))
  }
  this.dynamicFormService.getRest(url,token).subscribe(res => {
        //In res.data you have the data.
        //In res.dat.template_properties you has the array

        //Create the Form
        this.form = this.qcs.toFormGroup(this.questions);
        //Add so element at array as was necesary
        for (let i=0;i<this.data.myArray.length;i++)
        {
            this.addControls('template_properties')
        }
        //Finally use patchValue
        this.form.patchValue(res.data);
    }

好吧,您的数据与this.questions不对应,并且您的property_origin存在问题(关于将convertOrigin转换为一系列checkBox的问题,让我花点时间-我稍后会更新此anwser-)

更新,请参阅stackblitz更新。创建新的问题类型以创建复选框列表复选框存在问题。 在Angular中,一个checkBox只能有两个值“ true”或“ false”。 直到我知道,attrib值都没有影响。

所以,我们不能做这样的事情

<input type="checkbox" value="car" formControlName="checkName">
<input type="checkbox" value="dog" formControlName="checkName">

如果选中两个值,则要获取“ checkName”数组['car','dog']。

我们如何解决这个问题? 我认为更好的主意是有一个formGroup像

<div formGroupName="checkName">
  <input type="checkBox" formControlName="car">
  <input type="checkBox" formControlName="dog">
</div>

所以,我们会得到一些像

   checkName={car:true,dog:false}

好吧,一项工作是制作一个新的QuestionType“ ListCheckBoxQuestion”

export class ListCheckBoxQuestion extends QuestionBase<string> {
  controlType = 'list-chekbox';
  options: {key: string, value: string}[] = [];

  constructor(options: {} = {}) {
    super(options);
    this.options = options['options'] || [];
  }
}

之后,我们可以更改dinamic-formquestion.component并添加一个新开关。 看到我们用question.key创建了一个formGroupName,在这个组中,我们使用“ options”创建了一个formControlName。

<div [formGroupName]="question.key"  *ngSwitchCase="'list-chekbox'" >
  <ng-container *ngFor="let opt of question.options">
  <input type="checkbox"  [formControlName]="opt.key">
                <label >{{opt.value}}</label>
  </ng-container>
</div>

好吧,最难的部分是我们创建表单(问题控制服务的toFormGroup函数

toFormGroup(questions: QuestionBase<any>[]) {
    let group: any = {};

    questions.forEach(question => {
      if (question.controlType=="array") {
         group[question.key]=new FormArray([]);
      }else if (question.controlType=="list-chekbox")
      { //We create a FromGroup using the options
        let controls:any={};
        for (let option of question.options)
             controls[option.key]=new FormControl(false);
        group[question.key]=new FormGroup(controls);
        console.log("*",question);
      }
      else {
       ...
      }
    });
    return new FormGroup(group);
  }

好吧,要做的就是将我们的form.value转换为data并将接收到的数据转换为form.value。

当我们收到类似[“ car”,“ dog”]的东西时,我们必须转换为{car:true,dog:true},当我们收到{car:true,dog:false}时,我们必须转换为[“ car”]。 我们必须使用地图

更新看看问题控制服务的功能toFormGroup。 此功能是创建表单的功能。 在上一个版本中,我们在数组中添加了很多行作为值的长度。 如果未指定值,请更改此功能以添加线性

questions.forEach(question => {
      if (question.controlType == "array") {
        group[question.key] = new FormArray([]);
        if (question.value) {
          if (question.children) {
            //If question.children we must to give "value" to the children
            //So the children has as value, the value given in dataArray
            for (let value of question.value) {
              Object.keys(value).forEach(key => {
                let qu = question.children.find(x => x.key == key)
                if (qu) {
                  qu.value = value[key];
                  qu.controlType = qu.elementType
                }
              })
              group[question.key].push(this.toFormGroup(question.children))
            }
          }
        } //Add this lines to add one line to the array if no 
          //value is indicated
    else {
      if (question.children) {
        question.children.forEach(qu => {
          qu.controlType = qu.elementType

        })
        group[question.key].push(this.toFormGroup(question.children))
      }
    }

使用patchValue设置要形成的数据

this.dynamicFormService.getRest(url,token).subscribe(res => {
   this.form.patchValue({
      template_desc: res.data.template_desc,
      template_name:  res.data.template_name,
    });
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM