Как получить правильное количество formsControl, которое соответствует имени моих столбцов моего объекта таблицы без необходимости писать трудно - PullRequest
0 голосов
/ 19 сентября 2019

Я хотел бы иметь возможность динамически создавать свои переменные, вместо того, чтобы записывать их жестко в методе createInput (), который я вставляю в свой formArray.

Вот мой dashboard.component.ts:

export class DashboardComponent implements OnInit {

  table: Table;
  listName: string[];

  formGroup: FormGroup;
  inputRows: FormArray;

constructor(public ps: ParameterService, private formBuilder: FormBuilder, 
private sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
    inputRows: this.formBuilder.array([this.createInput()])

    });
    console.log(this.formGroup);

    this.ps.getAllColumns().subscribe(res => {
      this.table = res;
      console.log(res);
    });
  }

  get formData() { return this.formGroup.get('inputRows') as FormArray; }

  createInput(): FormGroup {

  return this.formBuilder.group({
      TYPEPARA: '',
      ID_CATEPARA: '',
      ID_NATUPARA: '',
      ID_FORMPARA: '',
      LIBL: '',
      DSCR: '',
      DATEDEBUEFFE: '',
      DATEFIN_EFFE: '',
      MONTCONVEURO: '',
      VALEDEFA: '',
      LIBLEXTR: '',
      TEXTLONG: '',
      REGRVALEPOSS: '',
      INTR: '',
      CODEINIT: '',
      VALEINIT: '',
      TYPONOME: '',
      MAXIVALE: ''
    });
  }
}

Мой объект с именем столбца:

enter image description here

Ответы [ 4 ]

1 голос
/ 19 сентября 2019

Вы можете динамически добавлять форму управления, перебирая столбцы.

    test: any = {
        name: "test",
        columns: [{
          name: "test1",
          type: "varchar"
        }, {
          name: "test2",
          type: "varchar"
        }, {
          name: "test3",
          type: "varchar"
        }]
      };
    testForm: FormGroup;
    constructor(private fb: FormBuilder) {
      this.testForm = this.fb.group({});
      this.initForm();
    }

    createInput() {
       this.test.columns.map((column) => {
         this.testForm.addControl(column.name, new FormControl(''));
       });
       console.log(this.testForm);
    }
0 голосов
/ 20 сентября 2019

after creating a condition it runs the console.log (this.table) but it does not create me the new formControl

после создания условия он запускает console.log (this.table), но не создает мне новый formControl

0 голосов
/ 20 сентября 2019

В ответ на: вы должны вызвать его внутри метода подписки и переименовать тест в таблицу

import { Component, OnInit } from '@angular/core';
import { ParameterService } from '../service/parameter.service';
import { Table } from '../model/table.model';
import { FormControl, FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { Typpar } from '../model/typpar.model';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  typpar: Typpar;
  table: Table;
  fileUrl: any;

  formGroup: FormGroup;
  inputRows: FormArray;

  numberOfLineForm: FormGroup;

  // On injecte une instance de FormBuilder et de ParameterService en dépendance de notre component
  constructor(public ps: ParameterService, private formBuilder: FormBuilder, private 
sanitizer: DomSanitizer) { }

  ngOnInit() {
    // initialize our form using FormBuilder in the ngOnInit hook.
    // We’ll create a formGroup that allows the user to add new inputRows dynamically:
    this.formGroup = this.formBuilder.group({
      inputRows: this.formBuilder.array([this.createInput()])
      /*
        * Ci-dessus la clé inputRows est : les formulaires que l'on génère à la volée
        * grâce à la méthode formbuilder.array() d'Angular
        * qui prend en param la méthode createItem() que nous définissons plus bas
      */
    });
    console.log(this.formGroup);

    this.numberOfLineForm = this.formBuilder.group({
      numberOfLine: ['']
    });
    console.log(this.numberOfLineForm);

    this.ps.getAllColumns().subscribe(res => {
      this.table = res;
      this.createInput();
      console.log(this.table);
      // this.downloadSqlQuery();
    });

    this.ps.getAllParams().subscribe(res => {
      this.typpar = res;
      console.log(res);
    });
  }

  // Permet de récupéer formData dans la vue qui est une instance de FormArray
  get formData() { return this.formGroup.get('inputRows') as FormArray; }

  // method to create a form group as the first inputRow in our array
  createInput(): FormGroup {
    // Comment récupérer le bon nombre de formControl qui correspondent
    // aux nom de mes columns de mon objet Table sans avoir à les mettres en dure
    console.log(this.table);
    this.table.columns.map((column) => {
      this.formGroup.addControl(column.name, new FormControl(''));
    });
    return this.formGroup;
  }
0 голосов
/ 20 сентября 2019

вот метод createInput ():

import { Component, OnInit } from '@angular/core';
import { ParameterService } from '../service/parameter.service';
import { Table } from '../model/table.model';
import { FormControl, FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser';
import { Typpar } from '../model/typpar.model';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  typpar: Typpar;
  table: Table;
  fileUrl: any;

  formGroup: FormGroup;
  inputRows: FormArray;

  numberOfLineForm: FormGroup;

  // On injecte une instance de FormBuilder et de ParameterService en dépendance de notre component
  constructor(public ps: ParameterService, private formBuilder: FormBuilder, private  sanitizer: DomSanitizer) { }

  ngOnInit() {
    // initialize our form using FormBuilder in the ngOnInit hook.
    // We’ll create a formGroup that allows the user to add new inputRows dynamically:
    this.formGroup = this.formBuilder.group({
      inputRows: this.formBuilder.array([this.createInput()])
      /*
        * Ci-dessus la clé inputRows est : les formulaires que l'on génère à la volée
        * grâce à la méthode formbuilder.array() d'Angular
        * qui prend en param la méthode createItem() que nous définissons plus bas
      */
    });
    console.log(this.formGroup);

    this.numberOfLineForm = this.formBuilder.group({
      numberOfLine: ['']
    });
    console.log(this.numberOfLineForm);

    this.ps.getAllColumns().subscribe(res => {
      this.table = res;
      console.log(this.table);
     });

    this.ps.getAllParams().subscribe(res => {
      this.typpar = res;
      console.log(res);
    });
  }

вот сообщение об ошибке:

enter image description here

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