@Input is not working


#1

If you have a parent component with an object, and you use a selector to display a child component, you can pass the object to the child component this way in Angular 2:

In the parent.html
<child-component [nameOfObjectInsideChildComponent] = “nameOfObjectInsideParentComponent”>

Then in child.ts
@Input nameOfObjectInsideChildComponent: any;

But in Ionic 2, I’m having problems getting the object in the child component. I get no errors but my object is undefined. Maybe in Ionic this is done in a different way?

Thanks for your time!


#2

Can you post the html code of your child? It seems that your problem is the lifecycle.


#3

I can’t even console.log (nameOfObjectInsideChildComponent) on the constructor. I don’t have an html code on my child component yet because I don’t have a value in my object. I don’t think it’s going to be useful anyways.

Thanks for the reply!


#4

It is useful. Because constructor gets called before object has been passed in your component’s input.


#5

Do you mean parent or child .html?


#6

child html. I think, the constructor in your child just initialized your component but not the object passed.


#7

That’s correct. But what I don’t understand is that .html is just an interpretation of what we want to show from our .ts. I just saw that the parent .html doesn’t show anything, sorry it’s here:

<child-component [nameOfObjectInsideChildComponent] = “nameOfObjectInsideParentComponent”>


#8

<child-component [nameOfObjectInsideChildComponent] = "nameOfObjectInsideParentComponent"></child-component>


#9

this is inside your parent html?


#10

For example, in your child html

and child ts


#11

Yes, it’s on my parent component.html.


#12

Please see updated example.


#13

And did you make it work? Doesn’t work for me.


#14

I can’t help you with just a fragment of details.

I want to see your whole html and ts codes of your child.


#15

And yes, it’s working on me.


#16

Here is it.

parent.ts:
brands: CarBrandsInterface []; //this is populated by firebase and I have objects with good result

parent.html
<ion-list *ngFor = "let brand of brands"> <ion-list-header>{{brand.name}}</ion-list-header> <page-car-list [brand] = "brand.key"> </page-car-list> </ion-list>

child.ts

@Input () brand: string; constructor(public navCtrl: NavController) { console.log (this.brand); //I get a value of undefined here. Shouldn't it be the brand.key passed by the parent component? }

child.html
<ion-content padding> <ion-item *ngFor = "let car of cars"> <div>{{car.model}}</div> </ion-item> </ion-content>


#17

I’m very grateful that you are taking me so much time to help me, by the way. Thanks a lot.


#18

I don’t know if how you get the values of cars through input brand. But maybe you should try this.


#19

Sorry, I get those from firebase too. I can’t make it work. How is your parent.html?


#20

You should pass as another input the cars object generated by firebase too.