Reputation: 1
In the communication between parent and child components of angular, how to use variables decorated with @ input in child components? For example, the following code:
@input str : string;
Then I can use it in the ngoninit() function:
ngOnInit(): void {
console.log ("str is:", this.str );
}
It works normally, and I can see the content in the console. But if I want to use this variable in another place in this class, for example, in the following functions:
private _ str : string;
strVal(){
this._ str= this.str ;
console.log ( str is:", this._ str);
}
It can be compiled, but there is an error in the console, and the prompt is "undefined".
How to solve similar problems? thank you.
Upvotes: 0
Views: 98
Reputation: 410
First, to avoid the undefined
issue you can start by givint to your input
a default value.
@Input()
str = 'default'; // Or you can just let it empty ''
Why you are having the undefined
. In your code I see
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:")
Upvotes: 0
Reputation: 491
Try to write @Input() str: string;
Also make sure, that the function strVal();
is called.
An easy way to test this is to call the function in the ngOnInit()
ngOnInit(): void {
this.strVal();
}
Upvotes: 0