Home > Software design >  How to use a text input binding between my parent and my child component?
How to use a text input binding between my parent and my child component?

Time:06-19

I have an input binding between my parent and my child component.

I want my child component to show up a text, which is input by the parent component. But the browser is not showing the text. How can I make the browser show up the text immediately and what am I doing wrong?

child component controller:

export class myChild {
    @Input()
    public text: String = "";

    public showText: String = "";
    
    constructor() {
        this.showText = text;
    }
}

child component html:

<p>{{showText}}</p>

parent component html:

<my-child [text]="my test text"></my-child>

CodePudding user response:

Welcome to StackOverflow!

Your input binding works perfectly. So why does your application not show up your desired text "my test text"? What you are experiencing is a race-condition between your child components construction and the receive of it's input. Currently, this is happing:

  1. Your child component is injected into your parents component and your childs components lifecycle has started with its construction.
  2. The constructor of your child component runs it's code block, which is this.showText = text. At this point, your input variable text has its default starting value "".
  3. Your child component's @Input() binding for your text is executed. Now your text has the received input "my test text". Unfortunetly, your variable this.showText = text; has already run before.

This is why your child component has the empty string in its variable showText.

Solution: Instead of setting your showText variable inside the constructor, you can create a Input setter method inside your child component's controller, which will be executed undependently from your components lifecycle:

child component:
export class myChild {
    public showText: string = "";
    constructor() {}
    
    @Input()
    public text(value: string) {
        this.showText = value;
    }
}
  • Related