Angular FormGroup заполнить из ответа JSON - PullRequest
0 голосов
/ 02 июня 2019

Мне нужно было создать форму, которая могла бы обрабатывать 3 уровня массивов вложенных форм, определенных следующим образом:

export class Task {
  type        : string;
  description : string;
  role        : string;
  resources   : string[];
}

export class Phase {
  name  : string;
  tasks : Task[];
}

export class Module {
  name   : string;
  phases : Phase[];
}

export class Structure {
  modules : Module[];
}

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


  techniqueStruct : FormGroup;

  create() {

    this.form.structure = Object.assign({}, this.techniqueStruct.value);

    this.http.post<Technique>(`techniques`, this.form).subscribe(
      response => {
        this.toastr.success('Technique successfully created.', 'Success');
        this.router.navigate(['/']);
      },
      err => this.handleError(err)
    );

  }

Теперь, когда я хочу сделать запрос PUT и отредактировать Structure, мне нужно заполнить все поля формы, но у меня возникают проблемы с Structure объектами, которые имеют несколько Module объектов.

this.techniqueStruct.setValue({
  modules: this.form.structure.modules
})

Вышеуказанный вызов заполнит только индекс 0 и выдаст ошибку

ERROR Error: "Cannot find form control at index 1"

Как я могу убедиться, что каждый индекс заполнен?

** РЕДАКТИРОВАТЬ - FormGroup **

  form  : Partial<Technique> = {
    name                  : "",
    description           : "",
    rules                 : [],
    delivery_mode         : [],
    interaction           : [],
    interrelationship     : [],
    motivation            : [],
    participation         : [],
    performance           : [],
    resolution_scope      : [],
    feedback_use          : [],
    target_audience       : [],
    learning_objectives   : [],
    affective_objectives  : [],
    social_objectives     : [],
    structure             : null
  };

  ngOnInit() {

    this.createHandler();

    this.getAttributes();

    this.techniqueStruct = this.fb.group({
      'modules': this.fb.array([
        this.initMod()
      ])
    });

    this.sub = this.activeRoute.params.subscribe(params => {
      this.id = params['id'];
      this.populateForm();
    });

  }
  initMod() {
    return this.fb.group({
      'name': ['', [Validators.required]],
      'phases': this.fb.array([
        this.initPhase()
      ])
    });
  }

  initPhase() {
    return this.fb.group({
      'name': ['', [Validators.required]],
      'tasks': this.fb.array([
        this.initTask()
      ])
    });
  }

  initTask() {
    return this.fb.group({
      'type': '',
      'description': '',
      'role': '',
      'resources': []
    })
  }


  addMod() {
    const control = <FormArray>this.techniqueStruct.controls['modules'];
    control.push(this.initMod());
  }

  addPhase(imod) {
    const control = (<FormArray>this.techniqueStruct.controls['modules']).at(imod).get('phases') as FormArray;
    control.push(this.initPhase());
  }

  addTask(imod, ipha) {
    const control = ((<FormArray>this.techniqueStruct.controls['modules']).at(imod).get('phases') as FormArray).at(ipha).get('tasks') as FormArray;
    control.push(this.initTask());
  }

  deleteMod(index) {
    let control = <FormArray>this.techniqueStruct.controls['modules'];
    control.removeAt(index)
  }

  deletePhase(imod, ipha) {
    const control = (<FormArray>this.techniqueStruct.controls['modules']).at(imod).get('phases') as FormArray;
    control.removeAt(ipha);
  }

  deleteTask(imod, ipha, itask) {
    const control = ((<FormArray>this.techniqueStruct.controls['modules']).at(imod).get('phases') as FormArray).at(ipha).get('tasks') as FormArray;
    control.removeAt(itask);
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...