0

Am trying to add a component inside another component, am getting an error in form builder group as.

  • ERROR TypeError: Cannot read property 'group' of undefined
  • Cannot read property 'controls' of undefined

am posting my full code in plunker for your reference, please do help me to resolve this issue, sorry if it is a duplicated issue

Interface

export interface Customer {
    name: string;
    addressess: Address[];

}

export interface Address {
    street: string;
    postcode: string;

}

export interface ExtraFields {
  DOB:string;
  Designation:string;
         otherfields: ExtraFields[];
}

Componenet

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Injectable } from '@angular/core';
@Component({
    moduleId: module.id,
    selector: 'address',
    templateUrl: 'address.component.html',
})
export class AddressComponent {
    @Input('group')
    public adressForm: FormGroup;
    private _fb: FormBuilder
    constructor(){}


    ngOnInit() {
        this.adressForm = this._fb.group({
            extraspaces: this._fb.array([])
        });

        // add address
        this.addextraField();

        /* subscribe to addresses value changes */
        // this.myForm.controls['addresses'].valueChanges.subscribe(x => {
        //   console.log(x);
        // })
    }


    initextraField() {
        return this._fb.group({
            dob: ['', Validators.required],
            designation: ['', Validators.required]
        });
    }

    addextraField() {
        const control = <FormArray>this.adressForm.controls['extraspaces'];
        const addrCtrl = this.initextraField();

        control.push(addrCtrl);
    }

    // removeAddress(i: number) {
    //     const control = <FormArray>this.myForm.controls['addresses'];
    //     control.removeAt(i);
    // }
}

Template

<div [formGroup]="adressForm">
    <div class="form-group col-xs-6">
        <label>street</label>
        <input type="text" class="form-control" formControlName="street">
        <small [hidden]="adressForm.controls.street.valid" class="text-danger">
            Street is required
        </small>
    </div> 
    <div class="form-group col-xs-6">
        <label>postcode</label> 
        <input type="text" class="form-control" formControlName="postcode">
    </div>
         <div class="margin-20">
          <a (click)="addextraField()" style="cursor: default">
            Add +
          </a>
        </div>

            <div formArrayName="extraspaces">
          <div *ngFor="let ext of adressForm.controls.extraspaces.controls; let i=index" class="panel panel-default">
            <div class="panel-heading">
              <span>Address {{i + 1}}</span>
              <span class="glyphicon glyphicon-remove pull-right" *ngIf="adressForm.controls.extraspaces.controls.length > 1" (click)="removeAddress(i)"></span>
            </div>
            <div class="panel-body" [formGroupName]="i">
              <extrafield [extragroup]="adressForm.controls.extraspaces.controls[i]"></extrafield>
            </div>
          </div>
        </div>

</div>

1 Answer 1

3

Several issues in the AddressComponent are the cause of the aforementioned errors:

  1. _fb variable is not injected
  2. FormBuilder and Validators are not imported
  3. Incorrect addressForm model configuration

Basically, once you import the required types

import { FormGroup, FormBuilder, Validators } from '@angular/forms';

inject FormBuilder

constructor(private _fb: FormBuilder){}

and define the FormGroup correctly

this.adressForm = this._fb.group({ street: [''], postcode: [''], extraspaces: this._fb.array([]) });

everything will work just fine.

Check the modified plunkr:

http://plnkr.co/edit/wjj6FGFK1esqRQh5oEGY?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot for correcting mistakes, am having one more issue, I cant able to get the field values in below JSON representations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.