为什么我会收到此错误:"Cannot read properties of undefined (reading 'index')"?



我在模板中使用以下代码:

<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');
}
})
}

当我加载网站时,我在控制台看到这个错误:

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

为什么我得到这个错误?

@Output()selectedTabChange: EventEmitter。选项卡选择更改时触发的事件。

不要运行方法ngOnInit()selectedTabChange监听器-这是一个生命周期钩子自动运行在组件构建https://angular.io/api/core/OnInit#ngoninit,它不会被认为是良好的做法。为tab changeonTabChange()创建一个新方法,并将其命名为

当组件被创建ngOnInit()在TS文件中运行时,evt在哪里?它找不到,所以是undefinedevt没有在TS文件的任何地方声明,因此它会出错-事件只从模板发送。ngOnInit()在模板渲染之前运行,虽然可以给方法提供参数,但在你的情况下不需要。

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>

工作示例:https://stackblitz.com/edit/angular-kwakqv?file=src%2Fapp%2Ftab-group-basic-example.html

就像Joosep Part说的那样重新安排你的代码

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)">
注意:一般情况下尽量避免从。html中调用ngOnInit, ngOnInit应该只在组件的生命周期钩子中调用

相关内容

最新更新