Home > Back-end >  Why do I get this error: "Cannot read properties of undefined (reading 'index')"
Why do I get this error: "Cannot read properties of undefined (reading 'index')"

Time:06-30

I'm using this code in my template:

<mat-tab-group   mat-align-tabs="start"  (selectedTabChange)="ngOnInit($event)">

ngOnInit:

ngOnInit(evt: any) {
  this.api.getApi().subscribe( ({tool, beuty}) => {
    this.beu = beuty.slice(0,this.i =18);
    this.tools = tool.slice(0,this.i =18);
    if (evt.index === 0) { 
      console.log('ddd');
    }
  })
}

When I load the website I see this error in the console:

ERROR TypeError: Cannot read properties of undefined (reading 'index')

Why do I get this error?

CodePudding user response:

@Output() selectedTabChange: EventEmitter. Event emitted when the tab selection has changed.

Do not run method ngOnInit() with selectedTabChange listener - thats a lifecycle hook automatically run on component build https://angular.io/api/core/OnInit#ngoninit and it wouldn't be considered good practice to do so. Make a new method for tab change onTabChange() and name it accordingly.

When component is being created ngOnInit() runs in TS file, where is the evt? It can't be found, so its undefined. evt is not declared anywhere in TS file thus it errors - the Event is only sent from template. ngOnInit() is run before template is rendered and though it is possible to give params to the method it's not needed in your case.

 onTabChange(event: any) {
    console.log(event)
  }
<mat-tab-group (selectedTabChange)="onTabChange($event)">
  <mat-tab label="First"> Content 1 </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

Working example: https://stackblitz.com/edit/angular-kwakqv?file=src/app/tab-group-basic-example.html

CodePudding user response:

As Joosep Part says rearrange your code

ngOnInit(evt: any) {
  //in ngOnInit call to the function with and argument create "on fly"
  this.getData({evt:0})
}

getData(evt: any)
{
  this.api.getApi().subscribe( ({tool, beuty}) => {
    this.beu = beuty.slice(0,this.i =18);
    this.tools = tool.slice(0,this.i =18);
    if (evt.index === 0) { 
      console.log('ddd');
    }
}

<mat-tab-group mat-align-tabs="start (selectedTabChange)="getData($event)">

NOTE: In general try to avoid call to ngOnInit from .html, ngOnInit should be called only in the lifecycle hook of our component

  • Related