如何以模板,反应形式,数组中的数组访问

时间:2019-07-02 13:30:16

标签: angular forms ionic-framework

我是编程的初学者,我尝试了解自己在做什么错。 :)

我已经创建了一个反应式表单,其中包含一个字符串数组,该字符串数组包含一个字符串和一个字符串数组。

它看起来像这样: enter image description here

并且json文件如下所示:

void MainWindow::connectTcp()
{
    QByteArray data; // <-- fill with data

    _pSocket = new QTcpSocket( this ); // <-- needs to be a member variable: QTcpSocket * _pSocket;
    connect( _pSocket, SIGNAL(readyRead()), SLOT(readTcpData()) );

    _pSocket->connectToHost("127.0.0.1", 9000);
    if( _pSocket->waitForConnected() ) {
        _pSocket->write( data );
    }
}

void MainWindow::readTcpData()
{
    QByteArray data = pSocket->readAll();
}

我到达正确地创建FormGroup: enter image description here

我提交时看起来正确:

enter image description here

但是我没有到达要在模板中正确显示它的地方:(

page.ts:

  public dbData: any =  {
    'ITEMS':[
      {
        'NAME': 'Farine',
        'QUANTITY': ['140', '60']
      }]
  };

Page.html

export class Form2Page implements OnInit, OnDestroy {
  itemsForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.itemsForm = new FormGroup({
      'items': new FormArray([])
    });
    console.log('From initForm', this.itemsForm);
  }

  onFormSubmit() {
    console.log('Submit : ', this.itemsForm.value);
  }

  onAddItems() {
    const control = new FormGroup({ name: new FormControl(''),
                                    quantity: new FormArray([])});

    (<FormArray>this.itemsForm.get('items')).push(control);
    console.log('Add From', this.itemsForm);
  }

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

我还没有在Ionic中实现。但是您也可以在Ionic中使用完全相同的东西:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';

export interface Data {
  ITEMS: Array<Item>;
}

export interface Item {
  NAME: string;
  QUANTITY: Array<string>;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dbData: Data = {
    'ITEMS': [
      {
        'NAME': 'Farine',
        'QUANTITY': ['140', '60']
      }]
  };

  itemsForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.itemsForm = new FormGroup({
      'ITEMS': this.formBuilder.array(this.dbData.ITEMS.map(item => this.createItem(item)))
    });
  }

  onFormSubmit() {
    console.log('Submit : ', this.itemsForm.value);
  }

  onAddItems() {
    (<FormArray>this.itemsForm.get('ITEMS')).push(this.createItem({ NAME: '', QUANTITY: [] }));
  }

  addQuantity(i) {
    (<FormArray>(<FormArray>this.itemsForm.get('ITEMS')).at(i).get('QUANTITY')).push(this.formBuilder.control(''));
  }

  private createItem(item: Item) {
    return this.formBuilder.group({
      NAME: [item.NAME],
      QUANTITY: this.formBuilder.array(item.QUANTITY.map(item => this.formBuilder.control(item)))
    });
  }

}

在模板中:

<pre>{{ itemsForm.value | json }}</pre>

<form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">
  <button type="button" (click)="onAddItems()">New Item</button>
  <div formArrayName="ITEMS">
    <div *ngFor="let itemsCtrl of itemsForm.get('ITEMS').controls; let i=index">
      <h4>ITEMS</h4>
      <div [formGroupName]="i">
        <label>Name :
          <input type="text" formControlName="NAME">
        </label>
        <br>
        <div formArrayName="QUANTITY">
          <div 
            *ngFor="let item of itemsCtrl.get('QUANTITY').controls; let j = index">
            <label>Quantity :
              <input type="text" [formControlName]="j">
            </label>
            <br>
          </div>
          <button (click)="addQuantity(i)">Add Quantity</button>
        </div>
      </div>
    </div>
  </div>
  <button type="submit">Submit</button>
</form>

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:1)

您的代码中存在多个问题

请参阅固定代码here

  • 您需要向数组添加控件/表单,仅拥有任何空表单数组是不够的

  • 要将数据加载到表单中,您需要进行一些重构,因为您需要遍历所有项并将控件/表单添加到数组中

enter image description here