角-反应形式-FormArray

时间:2018-11-14 23:11:55

标签: angular angular-reactive-forms

我正在尝试使用Angular Reactive-FormArray添加多行。

在示例中,我有2个文本字段。输入数据后,单击添加按钮,我要将其添加到行中。

添加后,我无法清除数据输入2文本字段。 并且数组中最后添加的元素仍链接到数据输入。

在这种情况下适合使用FormArray还是我应该使用简单的方法

这是我的代码。

https://stackblitz.com/edit/jay-angular-reactive-array-mwhmcn

1 个答案:

答案 0 :(得分:1)

我没有了解FormArray的用途,因此我建议一种更简单的方法来实现您想要的。

将TS更改为:

export class AppComponent  {

  constructor(private fb: FormBuilder) { }
  public simpleArray = [];
  form: FormGroup;

  ngOnInit() {

    this.form = this.fb.group({
      country1: ['', Validators.required],
      service1: ['', Validators.required]
    });

  }

  add() {
    this.simpleArray.push(this.form.value);
    //this.form.reset();
    this.form.get('country1').setValue('');
    this.form.get('service1').setValue('');
  }


  deleteService(i) {
    this.simpleArray.splice(i,1)
  }
}

您的HTML应该是:

<form [formGroup]="form">
   <h3>Angular Reactive form -  FormArray Demo </h3>
   Form : {{ simpleArray | json}}
   <br/><br/>
   <div class="form-group">
      <label for="country">Country</label>
      <input required type="text" id="country" class="form-control" formControlName="country1" />
   </div>
   <div class="form-group">
      <label for="service">Serivce</label>
      <input required type="text" id="service" class="form-control" formControlName="service1" />
   </div>
   <br />
   <button type='button' class="btn btn-primary" (click)='add()'>Add Services</button>
   <br />
   <div >
      <div class='row' *ngFor="let line of simpleArray let i=index">             
         <input class='form-control col-md-2' [value]="line.country1" />
         <input class='form-control col-md-2' [value]="line.service1"/>
         <button class='btn btn-primary col-md-1' (click)="deleteService(i)">Delete</button>
      </div>
   </div>
   <br />
</form>

A working Stackblitz

相关问题