user7924031
user7924031

Reputation:

how to access the index value of formarray of angular, when nested formControls are placed in a separate component?

I followed a tutorial from the website link https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 , to make a reactive form with an ability to add multiple form controls and that worked well. I moved the nested form controls in a separate component as guided in the tutorial and i need to access the index value of the formarray from the parent component. I want this index value to set that in one of the formconrols default value here is my code in plnkr, http://plnkr.co/edit/ZjEuBWrmJDiRmP4FeCzv?p=preview

my separated day and description component,

import { Component, Input } from '@angular/core';
    import { FormArray, Validators, FormGroup } from '@angular/forms';    

    @Component({
        selector: 'day-and-daydescription',
        template: ` <div [formGroup]="formGroup">
                        <div class="form-group col-xs-4" >
                            <label for="text">Day</label>
                            <input  type="text" class="form-control" formControlName="day" [ngModel]="group.i + 1"  readonly>                    
                        </div>
                        <!--Day Description-->
                        <div class="form-group col-xs-4">
                            <label>Description</label>
                            <input  type="text" class="form-control" formControlName="description">
                        </div>  
                    <div>`
    })
    export class DayAndDescriptionComponent {
        @Input('group')
        public formGroup: FormGroup;
    }  

Please have a look at the whole code in plunker.

Upvotes: 1

Views: 989

Answers (1)

AVJT82
AVJT82

Reputation: 73357

As you yourself noticed, you can manipulate the whole form from the parent, no need to try and access the index from the child. Everything you perform to the form in the parent, will reflect in the child.

And regarding the error:

Expression has changed after it was checked.

This is normal and happens in dev mode. Excerpt from Expression ___ has changed after it was checked:

In short, when in dev mode, every round of change detection is followed immediately by a second round that verifies no bindings have changed since the end of the first, as this would indicate that changes are being caused by change detection itself.

It's the actual @Input in child that is causing this. You can trigger change detection manually and this error will be gone. Since we are dealing with an @Input, you can do this in ngOnChanges:

constructor(private ref: ChangeDetectorRef) { }

ngOnChanges() {
  this.ref.detectChanges()
}

Upvotes: 2

Related Questions