Search code examples
javascriptangularangular4-formsangular-validation

Angular 4 - cannot read property status of null while displaying validation error


I am trying to display validation errors for FormArray, I have contact_number and contact_name in the array. The fields are getting added dynamically successfully but when they are invalid then I need to show validation error but its gives following error:

ERROR TypeError: Cannot read property 'status' of null
    at Object.eval [as updateDirectives] (SignupComponent.html:82)
    at Object.debugUpdateDirectives [as updateDirectives] (services.ts:384)
    at checkAndUpdateView (view.ts:359)
    at callViewAction (view.ts:615)
    at execEmbeddedViewsAction (view.ts:580)
    at checkAndUpdateView (view.ts:360)
    at callViewAction (view.ts:615)
    at execComponentViewsAction (view.ts:559)
    at checkAndUpdateView (view.ts:370)
    at callViewAction (view.ts:615)

My component code is as follows:

ngOnInit() {
    this.createForm();
}

createForm() {
    this.userGroup = this.fb.group({
        'name': [null, Validators.compose(
            [
                Validators.required,
                Validators.pattern("^[a-zA-Z]*$")
            ]
        )],
        'email': [null, Validators.compose(
            [
                Validators.required,
                Validators.email
            ]
        )],
        'age': [null, Validators.compose(
            [
                Validators.required,
                Validators.pattern("^[0-9]*$"),
                Validators.min(18)
            ]
        )],
        'address': this.fb.group({
            'address_1': [null, Validators.required],
            'address_2': null,
            'city': [null, Validators.required]
        }),
        'contacts': this.fb.array([this.initContact()])
    });
    console.log(this.userGroup);
}

initContact() {
    return this.fb.group({
        contact_name: ['', Validators.required],
        contact_number: ['', Validators.required]
    });
}

My template code is as follows:

<div>
    <h4>Signup</h4>
    <div>
        <form [formGroup]="userGroup" #f="ngForm">
            <div class="form-group">
                <label for="name">Name</label>:
                <input type="text" formControlName="name" placeholder="Enter Name" />
                <span *ngIf="userGroup.get('name').touched && userGroup.get('name').status == 'INVALID'">
                <span *ngIf="userGroup.hasError('required','name')">Please enter name</span>
                <span *ngIf="userGroup.hasError('pattern','name')">Invalid name</span>
                </span>
            </div>

            <div class="form-group">
                <label for="email">Email</label>:
                <input type="text" formControlName="email" placeholder="Enter Email" />
                <span *ngIf="userGroup.get('email').touched && userGroup.get('email').status == 'INVALID'">
                    <span *ngIf="userGroup.hasError('required','email')">Please enter email</span>
                    <span *ngIf="userGroup.hasError('email','email')">Invalid email</span>
                </span>
            </div>

            <div class="form-group">
                <label for="age">Age</label>:
                <input type="text" formControlName="age" placeholder="Enter Age" />
                <span *ngIf="userGroup.get('age').touched && userGroup.get('age').status == 'INVALID'">
                    <span *ngIf="userGroup.hasError('required','age')">Please enter age</span>
                    <span *ngIf="userGroup.hasError('pattern','age')">Invalid age</span>
                    <span *ngIf="userGroup.hasError('min','age')">Min age should be 18 years</span>
                </span>
            </div>

            <div formGroupName="address">
                <h4>Adddress</h4>
                <div class="form-group">
                    <label for="address_1">Address 1</label>:
                    <input type="text" formControlName="address_1" placeholder="Enter Address 1" />
                    <span *ngIf="userGroup.get('address.address_1').touched && userGroup.get('address.address_1').status == 'INVALID'">
                        <span *ngIf="userGroup.hasError('required','address.address_1')">Please enter address line 1</span>
                    </span>
                </div>

                <div class="form-group">
                    <label for="address_2">Address 2</label>:
                    <input type="text" formControlName="address_2" placeholder="Enter Address 2" />
                </div>

                <div class="form-group">
                    <label for="city">City</label>:
                    <input type="text" formControlName="city" placeholder="Enter City" />
                    <span *ngIf="userGroup.get('address.city').touched && userGroup.get('address.city').status == 'INVALID'">
                        <span *ngIf="userGroup.hasError('required','address.city')">Please enter city</span>
                    </span>
                </div>
            </div>

            <div class="form-group" formArrayName="contacts">
                <label for="contacts">Contact</label>: <span><button (click)="addContact()">Add Contact</button></span>
                <div *ngFor="let cont of userGroup.controls.contacts.controls let i=index" [formGroupName]="i">
                    <div class="form-group">
                        <label for="contact_name" class="lbl_contact">Name</label>:
                        <input type="text" formControlName="contact_name" class="txt_contact" placeholder="Enter Name" />
                        <label for="contact_number" class="lbl_contact">Number</label>:
                        <input type="text" formControlName="contact_number" class="txt_contact" placeholder="Enter Number" />
                        <span *ngIf="userGroup.get('contacts.controls[i].controls.contact_name').touched && userGroup.get('contacts.controls[i].controls.contact_name').status == 'INVALID'">
                            <span *ngIf="userGroup.hasError('required','contacts.controls[i].controls.contact_name')">Please enter contact name</span>
                        </span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <button type="submit" [disabled]="!f.valid" class="btn btn-primary">Sign Up</button>
            </div>
        </form>
    </div>
</div>

I am not getting what is the error as it gives error only when I try to display the error for contact name or number.


Solution

  • there is issue with the way you are trying to get element , with below line

    userGroup.get('contacts.controls[i].controls.contact_name').touched
    

    this will not get interpreted with control it get interpreted as string.


    you need to access element like this, so your code should be like

       userGroup.controls.contacts.controls[i].controls.contact_name.status
    

    So as per code you first need to access from(userGroup) then go to the controls and cotacts fromarray, and as fromarray is set of element access it by index i and then refer individual element in that array contact_name

    Ans based on Reading of this article : Reactive Forms in Angular: Dynamically Creating Form Fields With FormArray