这个问题通常发生在尝试在组件中访问未定义的输入时。要解决此问题,可以在组件的NgOnInit生命周期钩子中添加一个空对象检查,以确保输入存在,然后再执行任何取决于输入的操作。以下是一个示例代码:
import { Component, OnInit, Input } from '@angular/core';
@Component({ selector: 'my-component', templateUrl: './my-component.component.html' }) export class MyComponent implements OnInit {
@Input() userInput: string;
ngOnInit() { if (!this.userInput) { this.userInput = ''; } // 继续执行其他操作,使用输入 }
}
在这个示例中,我们添加了一个检查以确保this.userInput存在。如果不存在,我们将其设置为空字符串。现在,您可以继续使用userInput属性,而不必担心它是否已定义。