【问题标题】:Add form array after scann a barcode扫描条码后添加表单数组
【发布时间】:2021-06-09 16:17:13
【问题描述】:

我正在尝试在将条形码扫描到 formGroup 后添加一个 formArray。我得到的结果是一个 json,我有创建表单数组的连接和方法(或者我相信)。我正在使用 Angular 12

这是我声明表单组的方式

kanbanPedidoForm = this.formBuilder.group({
    usuario: ['', Validators.required],
    fecha: ['', Validators.required],
    ruta: ['', Validators.required],
    estacion: ['', Validators.required],
    folio: ['', Validators.required],
    material_guid: this.formBuilder.array([]),
})

然后当我激活手机的摄像头或笔记本电脑的摄像头并扫描条形码时,我会提出服务器请求

SearchKanban(){
    // this.AddDetails();
    this.cargandoInformacion = true;
    this.despachadoresService.getScannedKanban(this.barcodeValue).subscribe(
        response => {
            this.kanbanBusquedaForm.reset();
            if(response.status == 'success'){
                this.tablaKanban = true;
                this.cargandoInformacion = false;
                this.kanbanInfo = response.kanban;
                this.kanbanNombre = response.kanban[0].kanban_nombre
                this.materiales = JSON.parse(response.material)
                this.infoMaterial = this.materiales[0].material_guid

                
            }
        },
        error => {
            console.log(<any>error);
        }
    )
}

然后我创建表单数组

get details(){
    return this.kanbanPedidoForm.get('material_guid') as FormArray;
}

AddDetails(){
    const detailsFormGroup = this.formBuilder.group({
      id: this.getNewId(),
      material: '',
      unidad_medida: '',
      descripcion: '',
      minimo: '',
      maximo: '',
      requerido: ''
    });
    this.details.push(detailsFormGroup);
}

这是我在回复中得到的

(2) [{…}, {…}]
0:
id: 1
material_guid:
active: "Y"
created_at: "2021-05-28T13:27:03.000000Z"
deleted_at: null
descripcion: "Descripcion 1"
material_guid: "ddef30f4-d1cd-4547-ae5e-d150e854e280"
nombre: "Material 1"
unidad_medida: "UM 1"
updated_at: "2021-05-28T13:27:03.000000Z"
__proto__: Object
maximo: 3
minimo: 1
__proto__: Object
1: {id: 2, material_guid: {…}, minimo: 1, maximo: 2}

在我的 HTML 中,我有一个表格,我想用我的 json 数据填充它

<form [formGroup]="kanbanPedidoForm" *ngIf="tablaKanban">
  <table class="table-striped">
    <thead>
      <tr>
        <th scope="col" colspan="6">Usuario: {{despachadorName}}</th>
        <th scope="col" colspan="1">Fecha: {{myDate | date: 'shortDate' }}</th>
      </tr>
      <tr>
        <th scope="col" colspan="2">Ruta: {{rutaName}}</th>
        <th scope="col" colspan="2">Estación: {{kanbanNombre}}</th>
        <th scope="col" colspan="2">No. Req: {{folio}}</th>
        <th scope="col" colspan="2">
          <a mdbBtn size="sm" gradient="blue" mdbWavesEffect>
            <mdb-icon fas icon="save"></mdb-icon>
          </a>
        </th>
      </tr>
      <tr>
        <th scope="col">Material</th>
        <th scope="col">Descripción</th>
        <th scope="col">UM</th>
        <th scope="col">Minimo</th>
        <th scope="col">Maximo</th>
        <th scope="col">Requerido</th>
      </tr>
    </thead>
    <tbody>
      <tr formArrayName="material_guid" *ngFor="let material of materiales; index as i;">
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'material' + i" formControlName='material' placeholder="Material">
        </td>
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'descripcion' + i" formControlName='descripcion' placeholder="Descripcion">
        </td>
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'unidad_medida' + i" formControlName='unidad_medida' placeholder="Unidad de medida">
        </td>
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'minimo' + i" formControlName='minimo' placeholder="Minimo">
        </td>
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'minimo' + i" formControlName='minimo' placeholder="Minimo">
        </td>
        <td [formGroupName]="i">
          <input class="requiredQty" type="text" [attr.id]="'maximo' + i" formControlName='maximo' placeholder="Maximo">
        </td>
        <td [formGroupName]="i">
          <input type="number" class="requiredQty" name="" formControlName='requerido' [attr.id]="'cantidad' + i">
        </td>
      </tr>
      
    </tbody>
  </table>
  <button type="button" class="btn btn-success" (click)="AddDetails()">
    <i class="fa fa-plus-circle" aria-hidden="true"></i>
    Agregar concepto
  </button>
</form>

希望有人能帮助我,我从 2 天开始就被困住了

【问题讨论】:

  • 看看这个 SO:stackoverflow.com/questions/67700663/…。当您需要使用 *ngFor 而不创建“html 标签”时(在您的情况下,您使用的是表格,因此您可以使用 ng-container:angular.io/guide/built-in-directives#ngcontainer
  • 我试试看,我忘记了一点......当我扫描条形码时,如果你能看到,我需要发送多少我要发送的东西,在 formArray 我已经这里有一个“requerido”字段,我需要看看我是否需要 1 或 3 个动态按钮

标签: javascript angular typescript angular-cli


【解决方案1】:

一步一步来。

创建一个返回formGroup的函数更好地添加FormArray中的数据

groupDetails(data:any=null){
  data=data ||{id: this.getNewId(),material: '',unidad_medida: '',
               descripcion: '',minimo: '',maximo: '',requerido: ''
    };
     return this.formBuilder.group({
      id: data.id,
      material: data.material,
      unidad_medida: data.unidad_medida,
      descripcion: data.descripcion,
      minimo: data.minimo,
      maximo: data.maximo,
      requerido: data.requerido
    });
}

您的 .html 应该遍历 FormArray.controls,忘记“材料”

你的 .html 应该是这样的

<tbody>
   <!--see that you first say the formArrayName, use a ng-container
        to not create extra tags-->
    <ng-container formArrayName="material_guid">

      <!--the *ngFor in the "tr", see that also include the formGroupName-->
      <tr *ngFor="let group of details.controls; index as i;" 
             [formGroupName]="i">

        <!--in each td your input with formControlName-->
        <td >
          <input class="requiredQty" type="text" [attr.id]="'material' + i" formControlName='material' placeholder="Material">
        </td>
        <td>
          <input class="requiredQty" type="text" [attr.id]="'descripcion' + i" formControlName='descripcion' placeholder="Descripcion">
        </td>
        <td>
          <input class="requiredQty" type="text" [attr.id]="'unidad_medida' + i" formControlName='unidad_medida' placeholder="Unidad de medida">
        </td>
        <td>
          <input class="requiredQty" type="text" [attr.id]="'minimo' + i" formControlName='minimo' placeholder="Minimo">
        </td>
        <td>
          <input class="requiredQty" type="text" [attr.id]="'minimo' + i" formControlName='minimo' placeholder="Minimo">
        </td>
        <td>
          <input class="requiredQty" type="text" [attr.id]="'maximo' + i" formControlName='maximo' placeholder="Maximo">
        </td>
        <td>
          <input type="number" class="requiredQty" name="" formControlName='requerido' [attr.id]="'cantidad' + i">
        </td>
      </tr>
   </ng-container>
</tbody>

好吧,我们要“喂”formArray。如果您收到响应数组,您可以使用

this.despachadoresService.getScannedKanban(this.barcodeValue)
   .subscribe(
        response => {
          //I imagine the json you show is really the response.material
          //Angular by defect received json objet
          //so I think that is not neccesary your JSON.parse, 
          //but really I'm not pretty sure -else use Json.parse(response.material).map(...)-
          this.details=new FormArray(response.material.map(x=>this.groupDetails(x)))
        })

看到我们使用 map 转换数组作为响应。数组响应的每个元素都转换为一个 formGroup - 使用函数 this.groupDetails- 我们说 details 是一个 FromArray 与 formGroup 的数组-

确实有一个问题,如果 requerido 是一个新属性,你的 json 没有属性“material”也没有“requerido”,稍微改变一下函数 groupDetails,有些像

groupDetails(data:any=null){
  //e.g.
  //If you use material_guid and not material
  //and requerido is true by defect.

  data=data ||{id: this.getNewId(),material_guid: '',unidad_medida: '',
               descripcion: '',minimo: '',maximo: ''
    };
     return this.formBuilder.group({
      id: data.id,
      material: data.material_guid, //<--see how use material_guid
      unidad_medida: data.unidad_medida,
      descripcion: data.descripcion,
      minimo: data.minimo,
      maximo: data.maximo,
      requerido: 0 //<--see how I wrote a value "ad hoc"
    });
}

注意:请注意,如果要在表格中添加新行,可以添加按钮和功能

addGroup(){
   this.details.push(this.groupDetails());
}

或者删除一行

removeLine(index){
   this.details.removeAt(index)
}

【讨论】:

  • 我需要如何声明this.details?如果我声明我在我的问题中的方式,这个trowme错误,如果我删除details中的get,显示其他错误
  • 尝试检查之前是否存在:get details(){return this.kanbanPedidoForm.?this.kanbanPedidoForm.get('material_guid') as FormArray:null} 并使用 *ngIf 如果为空则不显示表格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多