Search code examples
angularangular4-forms

Angular 4 dynamic reactive form on Drop down form API [add and remove]


I'm facing the issue in angular 4 projects I would be grateful If you find time to resolve the issue.

Objective

On the change of dropdown value we need to call API on the basis of returned value we need to populate form data. [API will follow same object structure]

  1. The for loop I have mentioned in the block is not running completely to empty the form controls array.

  2. I have gone through FormGroup and FormArray classes there is no method to remove All controls.

  3. May be approach is not correct, due to incomplete knowledge of angular4.

  4. Fragments of source code :

    availableToolsForNewEvnList: Array<ToolsForNewEvn>;
    selectedToolsForNewEvnList: Array<ToolsForNewEvn>;

    getProjects() { //Working Fine
        this.devopsToolService.getProjects()
            .subscribe(
            projectList => {
                this.projectList = projectList as Project[];
                this.projectList.slice(0, 1).map(p => {
                    this.selectedProject = p;
                    this.onChange(p);
                });
            },
            error => this.errorMessage = <any>error);
    }


    getDevopAllToolsPojo(projectId: number) { //Error Block
        this.devopsToolService.getDevopAllToolsPojo(projectId)
            .subscribe(
            projectAllToolList => {
                this.projectAllToolList = projectAllToolList as DevopToolsPojo[];
                let control = <FormArray>this.myForm.controls['devopToolsPojo'];//ERROR in this block:Start
                console.log("BEFORE" + control.length);
                console.log(control);
                for (let i = 0; i < control.length; i++) {
                    console.log("Loop [ " + control.length + " ]");
                    console.log(control);
                    control.removeAt(i)
                }
                console.log("AFTER" + control.length);
                console.log(control);//ERROR in this block:END
                projectAllToolList.forEach(p => {
                    const addrCtrl = this.initDevopToolsPojo(p);
                    control.push(addrCtrl);
                });
                this.myForm.patchValue(projectAllToolList); //Working Fine
            },
            error => this.errorMessage = <any>error);
        this.myForm.controls['projectId'].setValue(projectId);//Working Fine
    }

    getDevopToolsPojo(projectId: number) { //Working Fine
        this.devopsToolService.getDevopToolsPojo(projectId)
            .subscribe(
            projectToolList => {
                this.projectToolList = projectToolList as DevopToolsPojo[];
            },
            error => this.errorMessage = <any>error);
    }

    getNewDevopToolsPojo(projectId: number) { //Working Fine
        this.devopsToolService.getNewDevopToolsPojo(projectId)
            .subscribe(
            tl => {
                this.availableToolsForNewEvnList = tl as ToolsForNewEvn[];
            },
            error => this.errorMessage = <any>error);
    }

    onChange(selectedProject) { //Working Fine
        this.selectedProject = selectedProject;
        this.getDevopToolsPojo(selectedProject.projectId);
        this.getDevopAllToolsPojo(selectedProject.projectId);
        this.getNewDevopToolsPojo(selectedProject.projectId);
    }

    initDevopToolsPojo(p) { //Working Fine
        return this._fb.group({
            'devopToolId': [p.devopToolId],
            'url': [p.url],
            'userName': [p.userName],
            'password': [p.password],
            'accessKey': [p.accessKey],
            'secureKey': [p.secureKey],
            'toolName': [p.toolName],
            'toolId': [p.toolId],
            'toolDesc': [p.toolDesc],
            'configured': [p.configured],
        });
    }

    ngOnInit() {
        this.myForm = this._fb.group({
            'projectId': [''],
            'devopToolsPojo': this._fb.array([])
        });
        this.initDevopToolsPojo(new DevopToolsPojo());
        this.selectedProject = new Project();
        this.getProjects();
    }

    constructor(
        private devopsToolService: DevopsToolService,
        private _fb: FormBuilder
    ) {
        this.availableToolsForNewEvnList = new Array<ToolsForNewEvn>();
        this.selectedToolsForNewEvnList = new Array<ToolsForNewEvn>();
    }

Console logs:

**12:42:03.564 devops-tool.component.ts:70 ##BEFORE7

12:42:03.565 devops-tool.component.ts:71 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.569 devops-tool.component.ts:73 ##Loop [ 7 ]

12:42:03.571 devops-tool.component.ts:74 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.572 devops-tool.component.ts:73 ##Loop [ 6 ]

12:42:03.573 devops-tool.component.ts:74 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.574 devops-tool.component.ts:73 ##Loop [ 5 ]

12:42:03.575 devops-tool.component.ts:74 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.576 devops-tool.component.ts:73 ##Loop [ 4 ]

12:42:03.577 devops-tool.component.ts:74 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.578 devops-tool.component.ts:77 ##AFTER3** 

***//There are 3 more records to be remove form list.*

12:42:03.580 devops-tool.component.ts:78 FormArray {validator: null, asyncValidator: null, _pristine: true, _touched: false, _onCollectionChange: function…}

12:42:03.583 devops-tool.component.ts:80 (7) [Object, Object, Object, Object, Object, Object, Object]**

Solution

  • If you are using a Form array you can set the controls to an empty array:

    removeAllQuestions() {
      console.log(this.myForm.get('devopToolsPojo'));
      this.questionForm.get('devopToolsPojo').controls = [];
      console.log(this.myForm.get('devopToolsPojo'));
    }
    

    Live plunker demo