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

10,830

Solution 1

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.

Solution 2

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" >
Share:
10,830
Owais Ahmed Khan
Author by

Owais Ahmed Khan

Updated on June 09, 2022

Comments

  • Owais Ahmed Khan
    Owais Ahmed Khan almost 2 years

    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)
    
  • Owais Ahmed Khan
    Owais Ahmed Khan almost 4 years
    it won't solve my problem as it doesnt render any input fields then
  • ruth
    ruth almost 4 years
    Then there should be an issue with the condition temp1[i]?.name. Including the safe navigation operator only makes sure temp1[i] is defined. So if you need the condition to pass, you need make sure temp1[i] is defined.
  • Owais Ahmed Khan
    Owais Ahmed Khan almost 4 years
    well, it worked after i remove ngif from the input field