Angular4 FormArray的removeAt函数关闭模态

时间:2017-08-10 13:22:27

标签: angular

我的angular4应用程序有问题。有一个用ng2-modal包制作的模态。模态包含一个反应形式,由一些FormGroups和FormArray组成。我可以动态添加和删除此FormArray中的元素。从此FormArray中删除元素使用函数removeAt,问题是当使用此函数时它会关闭模态。有人知道如何防止这种情况吗?

import {Component, OnInit, ViewChild, Input, OnChanges, EventEmitter, Output} from '@angular/core';
import {Validators, FormControl, FormGroup, FormArray} from '@angular/forms';


@Component({
  selector: 'modal-component',
  template: require('./modal-component.html')
})
export class ModalComponent implements OnInit, OnChanges {
  @ViewChild('modal') modal;
  @Input() myObject;
  @Output() updateMyObjectEmitter: EventEmitter<any> = new EventEmitter();
  public myForm: FormGroup;

  constructor() {}

  ngOnInit() {
    this.myForm = new FormGroup({});
  }

  ngOnChanges(changes) {
    this.myObject = changes.myObject.currentValue;
    if (changes.myObject.currentValue != null) {

      this.myForm = new FormGroup({
        id: new FormControl(this.myObject.id, [Validators.required]),
        content: new FormControl(this.myObject.content, [Validators.required]),
        options: new FormArray(this.myObject.options ? this.prepareOptionFormGroups(this.myObject.options) : [])
      });
    }
  }

  prepareOptionFormGroups(options): [] {
    let result = [];
    for (let i = 0; i < options.length; i++) {
      result.push(new FormGroup({
        id: new FormControl(options[i].id, [Validators.required]),
        value: new FormControl(options[i].value, [Validators.required])
      }));
    };
    return result;
  }


  addOption(): void {
    const control = <FormArray>this.myForm.controls['options'];
    control.push(this.initializeOption());
  }

  initializeOption(): any {
    return new FormGroup({
      value: new FormControl('Option', Validators.required)
    });
  }

  removeOption(index) {
    const control = this.myForm.controls['options'];
    control.removeAt(index);
  }

}

1 个答案:

答案 0 :(得分:0)

尝试使用event.preventDefault();。在您的组件代码中将代码修改为

removeOption(index,event:Event) {

    const control = this.myForm.controls['options'];
    control.removeAt(index);
    event.preventDefault();
    return false;

  }

让我知道它是否无效