生成形式槽循环 [英] Generate form trough loop

查看:20
本文介绍了生成形式槽循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过循环生成一个表单组,所以我有一些输入,并基于此创建一个带有嵌套组的表单.我接近它的想法是这样的:

Im trying to generate a form group by loop so I have some input and based on that it will create a form with nested group. My thought of aproaching it was this:

public transactionOrRefundRequestForm: FormGroup = new FormGroup({});

this.transactionOrRefundRequestForm.addControl('SaleToPos', new FormGroup(
      this.generateForm(this.formStructure)
    ));


 public generateForm(formEntry: FormEntry[] | null | undefined): any {

  formEntry.forEach(fe => {
    console.log(fe);
    console.log(this.transactionOrRefundRequestForm.controls);

    if (fe instanceof FormCategory) {
      const fc = fe as FormCategory;

     return {fc.name : new FormGroup(this.generateForm(fc.entries))};
    }

    if (fe instanceof FormInput || FormInputSelect || FormInputBoolean) {
      const fi = fe as FormInput;
 
      return {fi.name: new FormControl('')};
    }

  });

}

因此,当我获得输入时,它将循环遍历它,如果输入它,它将返回新的 formControl,但如果它是类别,它将返回带有子项的新 FormGroup,这些子项将被函数再次循环.

So when I get input it will cycle trough it and if it's input it will return new formControl but if it's category it will return new FormGroup with children that will be looped again by the function.

现在我的结果是一个空表格,但我不确定我做错了什么.

Right now my result is an empty form but i'm not really sure what am I. doing wrong.

这是一个堆栈闪电战:https://stackblitz.com/edit/angular-ivy-nqndkq?file=src/app/app.component.ts

它为没有构造函数的类抛出错误,但对我来说它工作得很好.Sooooo我不知道在那里做什么,抱歉.

It throws error for the class with no constructor but for me it works just fine. Sooooo I don't know what to do there, sorry.

推荐答案

这也部分包含了问题的解决方案 从表单生成表格

This also partly contains solution for question Generate table from form

所以我设法递归地生成它,这就是如何,代码有点长所以如果你迷路了回复我,我会尝试编辑它并更好地澄清它:

So I managed to generate it recursively and this is how, the code is a bit longer so if you get lost reply to me and I will try to edit this and clarify it better:

所以首先生成您的默认表单结构.

So first generate your default form structure.

我的看起来像这样:

this.formStructure =
      new FormCategory(
        'SaleToPOIRequest',
        [
          new FormCategory(
            'AdminRequest',
            [
              new FormInput('ServiceIdentification', '', [Validators.required]),
            ])
        ]);

然后是逻辑:

生成默认表单后我this.reconstructForm();

 private reconstructForm(): void {
    const oldValue = this.rebootRequestForm.value;
    this.rebootRequestForm = new FormGroup({});
    this.generateFormBranch(this.rebootRequestForm, [this.formStructure]);
    this.rebootRequestForm.patchValue(oldValue);
  }

那会触发this.generateFormBranch()

public generateFormBranch(parent: FormGroup, structure: FormEntry[]) {
    structure.forEach(formEntry => {
      if (formEntry instanceof FormInput) {
        parent.addControl(this.toInput(formEntry).name,
          new FormControl(this.toInput(formEntry).defaultValue, this.toInput(formEntry).validation));
      }
      if (formEntry instanceof FormCategory) {
        const formGroup = new FormGroup({});
        this.generateFormBranch(formGroup, formEntry.entries);
        if (formEntry.parent) {
          parent.addControl(formEntry.name, formGroup);
        } else {
          this.rebootRequestForm.addControl(formEntry.name, formGroup);
        }
      }
    });
  }

这将为我生成表单,我可以像这样添加类别和输入:

This will generate the form for me and I can add Category and Input like this:

public addCategory(parent: FormCategory): void {
    const dialogRef = this.dialog.open(FormUpdateDialogComponent, {
      data: <FormUpdateDialogComponent> {
        dialogType: 'category',
      }
    });
    dialogRef.afterClosed()
      .subscribe(data => {
        this.checkAndAddFormControl(parent, data, FormCategory);
      });
  }

  public addInput(parent: FormCategory): void {
    const dialogRef = this.dialog.open(FormUpdateDialogComponent, {
      data: <FormUpdateDialogComponent> {
        dialogType: 'input',
      }
    });
    dialogRef.afterClosed()
      .subscribe(data => {
        this.checkAndAddFormControl(parent, data, FormInput);
      });
  }

两者都会触发:this.checkAndAddFormControl()

checkAndAddFormControl(parent: FormCategory, name: string, type) {
    let isAvailable = true;
    parent.entries.forEach(entry =>
      entry.name === name ? isAvailable = false : isAvailable);

    if (type === FormInput) {
      if (isAvailable && name !== '') {
        parent.addEntry(new FormInput(name, '', []));
        this.reconstructForm();
        this.snackBar.open('Input ' + name + ' has been added at top of the category', 'OK');
      } else {
        this.snackBar.open('Name has already been set or it\'s null', 'OK');
      }
    }

    if (type === FormCategory) {
      if (isAvailable && name !== '') {
        parent.addEntry(new FormCategory(name, []));
        this.reconstructForm();
        this.snackBar.open('Category ' + name + ' has been added at the bottom of the category', 'OK');
      } else {
        this.snackBar.open('Name has already been set or it\'s null', 'OK');
      }
    }
  }

这篇关于生成形式槽循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆