如何在Angular父子通信中使用@input变量



在angular的父组件和子组件之间的通信中,如何在子组件中使用用@input修饰的变量?例如,以下代码:

@input str : string;

然后我可以在ngoninit((函数中使用它:

ngOnInit(): void {
console.log ("str is:",  this.str );
}

它工作正常,我可以在控制台中看到内容。但是,如果我想在这个类的另一个地方使用这个变量,例如,在以下函数中:

private _ str : string;
strVal(){
this._ str= this.str ;
console.log ( str is:", this._ str);
}

它可以编译,但控制台中出现错误,提示为"未定义";。

如何解决类似的问题?非常感谢。

必须将()用于Input。示例:

@Input() data: string

尝试写入@Input() str: string;

还要确保调用了函数strVal();

一个简单的测试方法是调用ngOnInit()中的函数

ngOnInit(): void {
this.strVal();
}

首先,为了避免undefined问题,您可以先为input设置一个默认值。

@Input()
str = 'default'; // Or you can just let it empty '' 

为什么要使用undefined。在你的代码中,我看到

console.log ( str is:", this._ str); // There is a " missing here
console.log ( "str is:", this._ str); // I think the undefined you are having,
// is not about the str input but about the "str" in this line where " was missing (str is:")

最新更新