Angular 9 - ERROR TypeError: Cannot read property 'name' of undefined

Viewed 11866

I am trying to create a dynamic form-control, I want some controls to be disabled based on the condition, but I get Type error of undefined. here is my code for it.

ngOnInit(): void {

 this.dynamicForm = this.formBuilder.group({
      tickets: new FormArray([])
  });
  }
  get f() { return this.dynamicForm.controls; }
  get t() { return this.f.tickets as FormArray; }

       itemClick(node) {

for (let i = 0 ; i < this.data_tree.length; i++) {
         this.nestsort.push(Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(this.data_tree[i])))
      var check
         rights.forEach(element => {
          if(element == this.temp[i].id)
          {
           check = false
          }
          else{
            check = true;
          }


        });
         this.t.push(this.formBuilder.group({
          name: ({value: [this.nestsort[i][aisa]], disabled: check})   

  }));      




         this.temp1 = this.t.value;


     }


} 

now if I don't use else condition and only if it doesn't give me an error but It only renders the disabled input fields.

this is my HTML code

<div *ngFor="let ticket of t.controls; let i = index">
              <div [formGroup]="ticket">
                  <div>
                      <mat-form-field *ngIf="temp1[i].name" appearance="outline"  style="width: 95%;">
                        <mat-label>{{temp[i].id}} </mat-label>
                      <input matInput type="text" placeholder="Name"  formControlName="name" class="form-control"/>
                      <!-- <mat-hint >Errors appear instantly!</mat-hint> -->
                    </mat-form-field>

I just want to create the input fields and some of them should be disabled because user don't have permission to change it, but it cant seems to create these fields and give me an error. the error is as follows,

navbars.component.html:77 ERROR TypeError: Cannot read property 'name' of undefined
    at Object.updateDirectives (navbars.component.html:79)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:46970)
    at checkAndUpdateView (core.js:45981)
    at callViewAction (core.js:46347)
    at execEmbeddedViewsAction (core.js:46304)
    at checkAndUpdateView (core.js:45982)
    at callViewAction (core.js:46347)
    at execEmbeddedViewsAction (core.js:46304)
    at checkAndUpdateView (core.js:45982)
    at callViewAction (core.js:46347)
3 Answers

The temp1 variable may not be defined when you try to access it in the template. You could use the safe navigation operator ?. to workaround the error.

<mat-form-field *ngIf="temp1[i]?.name" appearance="outline"  style="width: 95%;">

It checks if temp1[i] is defined before trying to access it's properties.

Use 'Elvis Operator'. It is very useful to protect against undefined and null values in property paths. This operator allows us to navigate an object path in situations when we are not aware whether a path exists or not. It returns value of the object path if it exists, else it returns the null value. It is very useful to prevent null-reference exceptions.

<mat-form-field *ngIf="temp1[i]?.name" appearance="outline" >

In place of

<mat-form-field *ngIf="temp1[i].name" appearance="outline" >

Maybe it is because when the template is rendered the temp1 object does not exists yet, then a quick suggestion, try to changue the conditional to this in all the cases you need to check if temp1[i].name exists: *ngIf="temp1 && temp1[i] && temp1[i].name" then if temp1 does not exists yet, you wont get any error :).

Related