Форма мастера шагов - PullRequest
       1

Форма мастера шагов

0 голосов
/ 15 ноября 2018

Я делаю угловое приложение с угловой динамической формой, где мне нужно разделить форму на две части.

В которой у меня есть поле ввода 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 / typcript, и нет jquery .. Как вы могли видеть в моей демонстрации, я не включал ни библиотеку, ни jquery ..

Пожалуйста, помогите мнечтобы добиться результата .. Застрял надолго ..

Ответы [ 4 ]

0 голосов
/ 15 ноября 2018

Если вы хотите создать пошаговую форму, вы можете спроецировать форму и использовать formcontrol для подключения родительской группы.

ParentComponent.ts


следующий
<div class="step container" *ngIf="form.valid && nextForm" >
 <form [formGroup]="step2">
  <app-step2 (control)="enableSave($event)"></app-step2>
  <button class="btn btn-primary"  (click)="moveToPrevious()" >Previous</button>
</form>
</div>
<hr>
<button
[disabled]="eSave"
 class="btn btn-primary" (click)="save()">Save</button>
</app-stepper-wrapper>

ParentComponent.ts

name = 'Angular';
  eSave = true;
  form = new FormGroup({});
  step2 = new FormGroup({});
  nextForm = false;

  ngOnInit() {
    this.form.statusChanges.subscribe(s => this.eSave = true);
  }   
  moveToNext() {
    if (this.form.valid) {
      this.nextForm = true;
    }
  }   
  moveToPrevious() {
    this.nextForm = false;
  }
  save() {
    console.log(this.form);
    console.log(this.step2);
  }
  enableSave($event) {
    if ($event == 'VALID' && this.form.valid) {

      this.eSave = false;
    }
  }

Пример: https://stackblitz.com/edit/angular-nynvvr

0 голосов
/ 15 ноября 2018

Итак, вы хотите удалить последний добавленный элемент управления email and dropdown из form group array.

Я добавил код в функцию goBack() для удаления элементов управления дочерней группы форм.

Компонент:

  goBack() {
    //Function to move to previous step
    if(this.form.controls['myArray']){      
      const arr = <FormArray>this.form.controls.myArray;
      arr.removeAt(arr.length - 1);
    }
  }

Рабочая демоверсия : https://angular -x4a5b6-cc4kyr.stackblitz.io

0 голосов
/ 15 ноября 2018

Передайте массив в методе 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)

  }
0 голосов
/ 15 ноября 2018

Постарайтесь достичь ваших требований: за исключением части пользовательского интерфейса.Я надеюсь, что вы можете обрабатывать ваш пользовательский интерфейс как ваше требование.

TS:

<code>    import { Component, Input, OnInit } from '@angular/core';
    import { FormGroup, FormArray } from '@angular/forms';

    import { QuestionBase } from './question-base';
    import { QuestionControlService } from './question-control.service';

    @Component({
      selector: 'app-dynamic-form',
      templateUrl: './dynamic-form.component.html',
      providers: [QuestionControlService]
    })
    export class DynamicFormComponent implements OnInit {

      @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, index: any) {
        let array = this.form.get('myArray') as FormArray;
        if (array.length > this.page) {
          this.page = this.page + 1;
        } else {
          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.page = this.page + 1;
        }
      }
      removeControls(control: string) {
        let array = this.form.get(control) as FormArray;
        array.removeAt(array.length - 1);
      }

      goBack() {
        if (this.page > 0) {
          this.page = this.page - 1;
        }
        //let array = this.form.get('myArray') as FormArray;
        //array.removeAt(array.length - 1);
        //Function to move to previous step
      }

    }

HTML : 

<div>
    <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">
            <ng-template [ngIf]="i + 1 == page"> 
              <div *ngFor="let item of question.children">
                <app-question [question]="item" [form]="form.get(question.key).at(i)"></app-question>
              </div>
            </ng-template>
                    </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',i)"> Next </button> 

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

  <pre>
{{form?.value|json}}

Это поможет вам показывать по одной странице за раз.Он создаст новый, если не существует следующей формы.И при нажатии на предыдущий он перейдет к старой форме.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...