我的angular4应用程序有问题。有一种使用ng2-modal软件包制作的模式。模态包含一个由一些FormGroups和FormArray组成的反应形式。我可以添加和删除这个FormArray的动态元素。从这个FormArray中移除元素使用removeAt函数,问题是当使用这个函数时,它会关闭模态。有人知道如何防止这种情况吗?Angular4 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);
}
}
请发表您的代码.. –
@vikk我刚刚发布的代码 –
您可以尝试传递'$ event'到您的'removeOption'函数并执行$ event.preventDefault()'? – Lansana