首页 > 解决方案 > 使用角度 8 的反应形式提交对象数组

问题描述

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

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

  employeeForm!: FormGroup;
  locations: Array<string>= ['Pune', 'Hyderabad', 'Noida']; 
  skills:  Array<ChoiceClass> = [
    {description: 'descr1', value: 'value1'},
    {description: "descr2", value: 'value2'},
    {description: "descr3", value: 'value3'}
  ];
  mat: MatrixDTO[] = [];
  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.initilazieForm();
    this.employeeForm.get('matrix')!.setValue(this.createBaseMatrix())
  }

  
  initilazieForm(): void {
    this.employeeForm = this.fb.group({
      name: 'Name here',
      gender: ['male', [Validators.required]],
      location: '',
      notes: '',
      email: '',
      skills: this.fb.array([], [Validators.required]),    
      matrix: this.fb.array([], [Validators.required]),  
      references: this.fb.array([this.fb.control('')])
    });
  }
  onSubmit(): void {
    console.log(this.employeeForm.value);

  }
  selectLocation(event:any):void{
    this.employeeForm.patchValue({
      location:event.target.value
    });
  }
  addEmail(): void {
    this.references.push(this.fb.control(''));
  }
  removeEmail(index: number): void {
    this.references.removeAt(index);
  }

  get references(): FormArray {
    return this.employeeForm.get('references') as FormArray;
  }

  onCheckboxChange(e:any) {
    const website: FormArray = this.employeeForm.get('skills') as FormArray;
  
    if (e.target.checked) {
      website.push(new FormControl(e.target.value));
    } else {
       const index = website.controls.findIndex(x => x.value === e.target.value);
       website.removeAt(index);
    }
  }

  createBaseMatrix(): MatrixDTO[] {
    this.mat[this.mat.length] = new MatrixDTO();
    this.mat[0].name = "Basic Weight(lbs/3000ft)";
    this.mat[0].customRow=false;
    this.mat[0].items.push({label:'30', customCol:false});
    this.mat[0].items.push({label:'35', customCol:false});
    this.mat[0].items.push({label:'40', customCol:false});
    
    
    this.mat[this.mat.length] = new MatrixDTO();
    this.mat[1] = new MatrixDTO();
    this.mat[1].name = "Basic Weight(g/m2)";
    this.mat[1].customRow=false;
    this.mat[1].items.push({label:'34', customCol:false});
    this.mat[1].items.push({label:'42', customCol:false});
    this.mat[1].items.push({label:'68', customCol:false});
    
    
    console.log(this.mat);
    return this.mat;
  }
  
}


export class MatrixDTO implements cols {
  constructor() {    
    this.name = "";
    this.items = [];   
    this.customRow = false;     
     this.label="";
     this.customCol=false;
  }
  name : string;
  items :Array<cols>;
  customRow:boolean;
  label: string;
  customCol:boolean;
  
}


interface cols {
  label: string;
  customCol:boolean;
}

export class ProductDTO {
  constructor() {
    this.id = "";
    this.name = "";     
  }

  id : string;
  name: string;
}

export class ChoiceClass {
  constructor() {
    this.description = "";
    this.value = "";     
  }

  description : string;
  value: string;
}

并且 HTML 如下:

 <p>employee works!</p>
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
 <label>
     Name : 
     <input type="text" formControlName="name" placeholder="required"/>
 </label>

 <label>
    Location : 
    <select formControlName="location" (change)="selectLocation($event)">
        <option *ngFor="let loc of locations" [value]="loc">
                {{loc}}
        </option>
    </select>
</label>
<label>
  <input type="radio" value="Male" formControlName="gender">
    <span>male</span>
</label>
<label>
  <input type="radio" value="Female" formControlName="gender">
    <span>female</span>
</label>
<h2>Please select what skill you're comfortable working with, if any:</h2>
<label for="website">Website:</label>
<div *ngFor="let skill of skills">
  <label>
    <input type="checkbox" [value]="skill.value" (change)="onCheckboxChange($event)" />
    {{skill.description}}
  </label>
</div>

  <h2>Reference(s)</h2>
  <div formArrayName="references" class="grouping" *ngFor="let ref of references.controls; let i=index">
    <label>
      Reference Email: 
      <input type="text" placeholder="optional" [formControlName]="i">
      <button type="button" id="remove_email"(click)="removeEmail(i)">X</button>
    </label>
  </div>
  <button type="button" (click)="addEmail()">Add Another Reference</button>
    <button id="apply_button">Save</button>
</form>

** 如何以反应形式传递对象的矩阵数组?以及当用户在同一屏幕上进行编辑时如何设置相同的信息**

编辑一:现在应用答案之一的建议后,我收到以下错误:

控制台错误

堆栈闪电战

标签: angular

解决方案


2 要记住的快速事项:

  1. 如果你想要一个反应形式的值,form.value不会给你你想要的。你可能想用这个:
const formValue = this.form.getRawValue();
console.log("Form Value ==>", formValue);
  1. 如果您想向表单控件添加内容,在 methodcreateBaseMatrix()中,您提到该方法的返回类型是createBaseMatrix(): void {},这意味着您没有返回任何内容。因此,在您的情况下,该值为 null 。

要更正此问题:更改该方法的返回类型,并确保您正在返回某些内容,然后通过执行以下操作分配给 formControl:

createBaseMatrix(): yourReturnType {}

this.form.get('matrix').setValue(this.createBaseMatrix())

// You can use, setValue or patchValue if you are doing it outside the form.

推荐阅读