2017-08-10 31 views
0

我的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); 
    } 

} 
+0

请发表您的代码.. –

+0

@vikk我刚刚发布的代码 –

+0

您可以尝试传递'$ event'到您的'removeOption'函数并执行$ event.preventDefault()'? – Lansana

回答

0

好吧,在互联网上我已经研究的一段时间后,决定使用stopPropagation函数,它的工作!我的功能修改后看起来像这样:

removeOption(index, event: Event) { 
    const control = this.myForm.controls['options']; 
    control.removeAt(index); 
    event.stopPropagation(); 
} 

我想感谢大家试图帮助我。 :)

0

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

removeOption(index,event:Event) { 

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

    } 

让我知道,如果它不工作

+0

我已经将此代码添加到我的视图 button(type =“button”,(click)=“removeOption(index,$ event)”) 和您发布到模态组件,但它没有帮助。 –

+0

控制台中的任何错误? –

+0

更新了我的答案,只需检查一次 –