2
votes

I am trying to show child component after receiving data from parent component. I have make this steps to do it :

  1. I've declare the component selector in parent html page.
  2. Send the data from parent to the child component Show(text: string) method:

    private text: string;
    Show (text: string){
        this.text = text;
    }     
    
  3. So after that i insert *ngIf="text" for div in my child component to show data only when my component received it.

But when I call show method of my child component the text variable is empty and my child component doesn't shows. I think it is because child component selector in my parent html page create a new instance of object, that has an empty text value. How i can solve this ?

UPDATED

I am trying to use @Input. It's working. But working for string. How i can send to the input some class instance ?

1
Sending data from parent to child should be with @Input and not with a method - Vega
In template: [text]="text in child: @Input text: string; - Swoox
You can add an boolean isLoaded to your component, initialy false, use *ngIf with this boolean, and set it to true just after you do this.text = text - Pac0
A plunkr demonstrating the issue would be really helpful - Alex Beugnet

1 Answers

1
votes

An example of parent HTML (only needed part):

<your-child-selector [text]="parentText"></your-child-selector>

[text]-"parentText" will pass parentText variable value from parent to child variable text.

In child component you should use @Input to receive data from parent like this:

@Input text: string;

And if you don't want to display anything in child component, while it didn't receive text, you can add *ngIf to hide (exclude) a part of DOM. Something like this (in child component):

This *ngIf will not show anything, while the child component will not receive text variable (using @Input) from parent component.

P.S: Don't forget to import Input in your child component!