0

In a form in my Angular app, I am trying to display a div only if a certain condition is met.

When the page loads initially, there are no errors appearing in the console. And the below div is not appearing (as the ngIf is not true).

But, when I submit my form & reset() the form I am getting the following error:

ERROR TypeError: Cannot read property 'value' of null

Here is the code where the error is appearing:

<div class="axis-form-group">
          <label class="axis-control-label">Injury Type:</label>
          <axis-radio-button-wrapper (getSelectedItem)="getSelectedItem($event)" formControlName="injuryType"
            name="injuryType" updateOn="click">
            <axis-radio cid="Bumps, scratches & damage" class="_text-bold" name="insuredType"
              value="Bumps, scratches & damage" heading="Bumps, scratches & damage" data-orientation="inline">
            </axis-radio>
            <axis-radio cid="Replacement of windows etc." name="insuredType" value="Replacement of windows etc."
              heading="Replacement of windows etc." data-orientation="inline">
            </axis-radio>
            <axis-radio cid="Burglary in the car" name="insuredType" value="Burglary in the car"
              heading="Burglary in the car" data-orientation="inline">
            </axis-radio>
            <axis-radio cid="Destroyed roof box, bicycle etc." name="insuredType"
              value="Destroyed roof box, bicycle etc." heading="Destroyed roof box, bicycle etc."
              data-orientation="inline">
            </axis-radio>
            <axis-radio cid="Wrong fuel" name="insuredType" value="Wrong fuel" heading="Wrong fuel"
              data-orientation="inline">
            </axis-radio>
            <axis-radio cid="Theft of license plates" name="insuredType" value="Theft of license plates"
              heading="Theft of license plates" data-orientation="inline">
            </axis-radio>
          </axis-radio-button-wrapper>
        </div>

<div class="axis-form-group" *ngIf="damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType.value.value === 'Burglary in the car' || damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType.value.value === 'Theft of license plates'">
    <label class="axis-control-label" for="scAlarm">Damge reported to the police:</label>
    <axis-checkbox-wrapper formControlName="damageReportedToPolice">
        <axis-checkbox cid="Yes" heading="Yes" name="Yes" value="Yes"></axis-checkbox>
    </axis-checkbox-wrapper>
</div>  

It's failing on the following line:

*ngIf="damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType.value.value === 'Burglary in the car' 
|| damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType.value.value === 'Theft of license plates'"

Here is my ngOnInit():

ngOnInit() {
    this.damageDetailsTwoForm = this.fb.group({
        injuryTypeGp: this.fb.group({
            injuryType: new FormControl('', Validators.required),
            damageReportedToPolice: new FormControl(''),
            itemOwner: new FormControl(''),
            objectDescription: new FormControl(''),
        }),
    damageReported: new FormControl('', Validators.required),
    selfRiskAmount: new FormControl('', Validators.required),
    otherCompanyName: new FormControl('', Validators.required),
    policyNo: new FormControl('', Validators.required),
    });
}

And here is my getSelectedItem():

getSelectedItem(data) {
    console.log(data);
    if (data.value === 'Burglary in the car' || data.value === 'Theft of license plates') {
      // tslint:disable-next-line: max-line-length
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.setValidators(Validators.required);
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.clearValidators();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.clearValidators();
    } else if (data.value === 'Destroyed roof box, bicycle etc.') {
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.setValidators(Validators.required);
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.setValidators(Validators.required);
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.clearValidators();
    } else {
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.clearValidators();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.clearValidators();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.reset();
      this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.clearValidators();
    }
    this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].damageReportedToPolice.updateValueAndValidity();
    this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].itemOwner.updateValueAndValidity();
    this.damageDetailsTwoForm['controls'].injuryTypeGp['controls'].objectDescription.updateValueAndValidity();
  }

Can someone please tell me why this error is occurring & how to resolve it? Thanks a lot in advance!

0

2 Answers 2

1

You can use the safe navigation operator and avoid such errors on the template.

*ngIf="damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value.value === 'Burglary in the car.

Still, since it can't find the value, most probably it can't find the form control. See if the form is initialized at the current point

The other case is that since you reset your form, the control's value is set to null and you are trying to access the a property on an object that's not there. You can place the safe operator on the value property as well

*ngIf="damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value?.value === 'Burglary in the car.

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

7 Comments

Hi, thanks for your answer. I updated my code to this: <div class="axis-form-group" *ngIf="damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value.value === 'Burglary in the car' || damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value.value === 'Theft of license plates'"> but the same error is appearing on the same line
injuryType is in my ngOnInit() so it should be initialized to ''. How would i check if the control is initialized at that point?
When I submit the form, I call the reset() method on the form. As the injuryType FormControl is initialized in ngOnInit(), should it be initialized?
OK. Well you get an error saying Cannot read property 'value' of null and you got 2 value properties on 2 different objects. Either the control is undefined damageDetailsTwoForm['controls'].injuryTypeGp.controls.injuryType?.value or the value of the control is null. In the second case you got to place the safe operator on the value property
Since you reset the form, most probably the control's value is null and it's throwing an error because you are trying to access something deeper. I'll add this to the original answer
|
1

I'd try a get to abstract away that long conditional. Try something like this:

<div class="axis-form-group" *ngIf="validator">
  <label class="axis-control-label" for="scAlarm">Damge reported to the police:</label>
  <axis-checkbox-wrapper formControlName="damageReportedToPolice">
    <axis-checkbox cid="Yes" heading="Yes" name="Yes" value="Yes"></axis-checkbox>
  </axis-checkbox-wrapper>
</div>
ngOnInit() {
  this.damageDetailsTwoForm = this.fb.group({
    injuryTypeGp: this.fb.group({
      injuryType: ['', Validators.required],
      damageReportedToPolice: [''],
      itemOwner: [''],
      objectDescription: [''],
    }),
    damageReported: ['', Validators.required],
    selfRiskAmount: ['', Validators.required],
    otherCompanyName: ['', Validators.required],
    policyNo: ['', Validators.required],
  });
}


get validator() {
  const targetValues = ['Burglary in the car', 'Theft of license plates'];
  return targetValues.indexOf(this.damageDetailsTwoForm.get('injuryType').value.value) !== -1;
}

3 Comments

Thanks for your answer. I've added your solution to my code but I'm getting an error on this line: return targetValues.indexOf(this.damageDetailsTwoForm.get('injuryTypeGp').get('injuryType').value.value) !== -1; The error message is Cannot read property value of null
@user9847788 why are you calling value on value? Is it a nested value?
Yes, the 3rd party control I'm using has a nested value

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.