这通常是由于在初始化时未定义此属性而导致的。 当此属性被父组件传递给子组件时,子组件将尝试访问该属性,但由于它在初始化时未定义,因此会导致“ Cannot Read Property of null”错误。
要解决此问题,可以通过在子组件的ngOnInit()函数中初始化属性或通过在子组件的模板中使用安全导航运算符(?)来检查该属性是否存在。
例如:
parent.component.ts:
componentProperty: any = null;
parent.component.html:
child.component.ts:
@Input() childComponentProperty: any;
ngOnInit() { // initialize the property to an empty object if (!this.childComponentProperty) { this.childComponentProperty = {}; } console.log(this.childComponentProperty.property1.property2); }
或
child.component.html:
{{childComponentProperty?.property1?.property2}}
这样,如果属性“ property1”或“ property2”未定义,则不会引发“ Cannot Read Property of null”错误。
希望这可以帮助您解决问题!