Angular - 无法读取未定义属性(读取“CustomHeaderComponent”)

3

我刚刚在自己的项目中创建了一个新组件,但是我一直收到相同的错误信息。我确定注入代码是正确的,模块和组件导出逻辑也是正确的。我无法理解错在哪里。

custom-header.component.ts

import {Component, Input, ViewEncapsulation} from '@angular/core';
import {Router} from '@angular/router';

@Component({
  selector: 'custom-header',
  templateUrl: './custom-header.component.html',
  encapsulation: ViewEncapsulation.None
})
export class CustomHeaderComponent {

  @Input() parentPageTitle: string;
  @Input() pageTitle: string;
  @Input() createButtonName: string;
  @Input() createButtonFunction: () => void;

  /**
   * Constructor
   */
  constructor(
    private _router: Router,
  ) {
  }
}

custom-header.module.ts

import {NgModule} from '@angular/core';
import {CustomHeaderComponent} from 'app/modules';
import {MatButtonModule} from '@angular/material/button';
import {CommonModule} from '@angular/common';

@NgModule({
  declarations: [
    CustomHeaderComponent,
  ],
  exports: [
    CustomHeaderComponent,
  ],
  imports: [
    MatButtonModule,
    CommonModule,
  ]
})
export class CustomHeaderModule {
}

index.ts

export * from './header/custom-header.module';
export * from './header/custom-header.component';

错误信息

core.mjs:6485 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'CustomHeaderComponent')
TypeError: Cannot read properties of undefined (reading 'CustomHeaderComponent')
    at Module.CustomHeaderComponent (custom-header.module.ts:11:26)
    at custom-header.module.ts:8:5
    at Module.11151 (custom-header.module.ts:11:26)
    at __webpack_require__ (bootstrap:19:1)
    at Module.33630 (index.ts:8:60)
    at __webpack_require__ (bootstrap:19:1)
    at Module.3265 (ganymede-users.module.ts:22:30)
    at __webpack_require__ (bootstrap:19:1)
    at Module.50252 (custom-header.module.ts:11:26)
    at __webpack_require__ (bootstrap:19:1)
    at resolvePromise (zone.js:1213:1)
    at resolvePromise (zone.js:1167:1)
    at zone.js:1279:1
    at ZoneDelegate.invokeTask (zone.js:406:1)
    at Object.onInvokeTask (core.mjs:25505:1)
    at ZoneDelegate.invokeTask (zone.js:405:1)
    at Zone.runTask (zone.js:178:1)
    at drainMicroTaskQueue (zone.js:582:1)

我猜这是一种初始化问题(在解析CustomHeaderComponent之前读取它) - 可能是代码中某个地方(更高的位置)存在循环导入。改变index.ts文件中导出项的顺序可能会有所帮助。 - Ján Halaša
1个回答

0
使用OnChanges,因为它是一个生命周期钩子,在指令的任何数据绑定属性发生变化时都会被调用:
 import {Component, OnChanges, SimpleChanges, Input} from '@angular/core';



export class ChildComponent implements OnChanges {
 
  @Input() message = '';    
  
  ngOnChanges(changes: SimpleChanges) {
  
     if (this.message){
      //do something here....
      
     }
     
  }
  
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接