1

I have a simple component parent-child to pass a parameter.

in parent component: i get values from http request in a service:

this.Service.getdataId(this.dataId).subscribe(
        response => {
        this.DataSource = response;                    
        this.personid = response.PersonInfo.Id; // this is being bound to from template for @input parameter.
      }

in my parent template, I have:

<app-view [personid ]="personId"></app-view>

in my child template:

@Input() personid : string = "";

my child template, never gets the value. BUT, is chrome dev tools, i can see that the value was given to the element:

app-view _ngcontent-iwk-c94="" _nghost-iwk-c93="" ng-reflect-personid="1da772c6-640f-456c-bba8-c25633">

So, I can see it there, but it is not assigned to the Input variable in my component. Further to this, the value is cut off for some reason, it is supposed to be a GUID, and the last 6 characters are cut off..i have not manipulation of this value anywhere. It goes from teh HTTPClient/Service -> Parent Component->Child Component.

EDIT: I hooked up the OnChange event. It seems like teh value i changing multiple times. I console log the value in the Onchange and it goes twice - once time the value i am expecting is there, the second time it is not. Hope someone can explain the situation to me?

R123
  • 61
  • 3
  • 1
    Should it be `[personid]="personid"`? But I am sure that's a typo, still have no explanation. – AliF50 Mar 24 '20 at 01:11
  • Hi, yea, sorry, i was renaming stuff for the purpose of the post - i have all the naming correct in my code. I update the post. – R123 Mar 24 '20 at 13:49

2 Answers2

0

Sounds like you may be trying to access the value too early. Inputs are available during OnIni(), but not before.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
  • I'm not sure that is the issue. I am getting the results from the HttpClient-> assigning them to the local variable in the callback -> the local variable is bound to the child component property -> but in the OnInit of the child component property, the value was not available (is that the OnInit you mean?). I found that odd that the child component would not have the value in onInit. However, when I implemented the OnChange event in the child component, i was able to get the value there. So I moved my logic from OnInit to the OnChange in the child component. Is this the proper flow? – R123 Mar 24 '20 at 13:53
  • That works, but it's a bit heavyweight. I'd add a "set" method for the @Input, and move the logic there instead of OnChange, which typically gets called very frequently. – GreyBeardedGeek Mar 25 '20 at 14:04
0

Hooking into the onchange per my edit seems to solve it. the double call to onchange was rookie error with a line that had set the value to "". i guess the hook for oninit occurs to early before the property is bound therefore the need to use the onchange instead.

R123
  • 61
  • 3