首页 > 解决方案 > 步骤向导表单

问题描述

我正在使用角度动态形式制作角度应用程序,我需要将表单分成两部分。

我在第一页有输入字段firstname and lastname,然后单击下一个按钮email and dropdown需要加载的孩子..

html:

    <form (ngSubmit)="onSubmit()" [formGroup]="form">

        <div *ngFor="let question of questions" class="form-row">
            <ng-container *ngIf="question.children">
                <div [formArrayName]="question.key">
                    <div *ngFor="let item of form.get(question.key).controls; let i=index" [formGroupName]="i">
                        <div *ngFor="let item of question.children">
                            <app-question [question]="item" [form]="form.get(question.key).at(i)"></app-question>
                        </div>
                    </div>
                </div>
            </ng-container>
            <ng-container *ngIf="!question.children">
                <app-question [question]="question" [form]="form"></app-question>

            </ng-container>
        </div>

  <button (click)="goBack()"> Previous </button> &nbsp;
  <button (click)="addControls('myArray')"> Next </button> 

        <div class="form-row">
            <button type="submit" [disabled]="!form.valid">Save</button>
    </div>
  </form>

TS:

  @Input() questions: QuestionBase<any>[] = [];
  form: FormGroup;
  payLoad = '';

  page: number = 0

  constructor(private qcs: QuestionControlService) { }

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

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
  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))
  }
  removeControls(control: string){
    let array=this.form.get(control) as FormArray;
    array.removeAt(array.length-1);
  }

  goBack() {
    //Function to move to previous step
  }

工作演示

https://stackblitz.com/edit/angular-x4a5b6-p4agaq

在这个带有代码的演示中,您可以在每次单击添加按钮时看到子项(数组)被附加到同一页面的下面。

我也有removeControl功能,

  removeControls(control: string){
    let array=this.form.get(control) as FormArray;
    array.removeAt(array.length-1);
  }

需要明确的是,我现在不会使用它,也不会在任何地方删除任何东西。唯一的事情是点击下一个孩子通过addControl功能将孩子添加到下一页,然后返回上一步。

为了附加到演示中给出的同一页面,它应该移动到下一页并再次单击上一个它应该在每次下一次单击时回到原始状态它应该给出一个新的email and dropdown并且在上一个返回到上一步..

在来回移动时,它应该像具有滑动效果的滑块一样移动。

一切都需要纯角度和基于javascript/typescript,并且没有jquery ..正如您在我的演示中看到的那样,我没有包含任何库或jquery ..

请帮助我达到结果..卡了很长时间..

标签: javascriptangularformstypescriptangular-reactive-forms

解决方案


在要删除的 goBack 方法中传递数组

   <button (click)="goBack('myArray')"> Previous </button> &nbsp;    

将此方法放在组件ts文件中

  goBack(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).removeAt(children.length-1)

  }

推荐阅读