无法使用FormBuilder从使用FormArrayName的输入获取值

时间:2019-08-01 01:58:25

标签: angular

当尝试使用formArrayName从输入字段获取值时,它不返回任何值,但显示为null。 在我的控制台中,我从客户名中获得价值,但不是出于秘密。 我希望返回的值是一个只有1个值的数组,即[“ 1”]。 请帮忙!我是新来的。

form.component.ts

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<mat-form-field>
      <mat-label>Client Name</mat-label>
      <input type="text" matInput formControlName="clientName">
      </mat-form-field>
<mat-form-field>
        <mat-label>Secrets</mat-label>
        <input formArrayName="secrets" matInput>
</mat-form-field>
</form>
form.ts file
    ngOnInit() {
    this.registerForm = this.formBuilder.group({
      clientName: ['', Validators.required],
      secrets : this.formBuilder.array([]),
      });
  }

onSubmit() {
    console.log(this.registerForm.value);
    }

  Expected output in the console
    clientName: "Value typed in input",
    secrets: ["Value typed in input"] 
    in jSON
    {
        "clientName": "test client",
        "secrets": ["secret"]
    }

2 个答案:

答案 0 :(得分:0)

  

选中此working example

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  private formBuilder: FormBuilder;
  registerForm;
  items;
constructor(private fb: FormBuilder){

  this.registerForm = this.fb.group({
      clientName: ['', Validators.required],
      secrets : [this.createItem()],
      });

       console.log(this.registerForm.value);
}

createItem() {
  return this.fb.group({
    name: 'hello ',
    description: 'thiese',
    price: 'data'
  });
}
addItem(): void {
  this.items = this.registerForm.get('items') as FormArray;
  this.items.push(this.createItem());
}

}

答案 1 :(得分:0)

如果您的预期输出是:

{
  "clientName": "test client",
  "secrets": ["secret"]
}

您已经正确添加了一个formarray,但是您还需要在该数组中添加一个form控件。像任何数组一样,它的格式将为0(索引),因为数组中只有一项。因此,构建表单如下:

this.registerForm = this.formBuilder.group({
  clientName: ['', Validators.required],
  secrets: this.formBuilder.array([
    this.formBuilder.control('') // add a control
  ]),
});

然后,如注释中所述,在模板中,您不应将表单数组标记为输入,而应使用formControlName="0"。例如,应该在div或mat-form-field上标记formarray,如下所示:

<mat-form-field formArrayName="secrets">
  <mat-label>Secrets</mat-label>
  <input formControlName="0" matInput>
</mat-form-field>

现在您将获得所需的格式。 DEMO