Passing parameters to custom components

I’m trying to create a simple custom component in order not to replicate code but I’m having trouble passing parameters and accessing them from the component’s constructor. My component is called “match-cell”:

match-cell.ts:
import { Component, Input} from ‘@angular/core’;
import { NavController } from ‘ionic-angular’;

@Component({
selector: ‘match-cell’,
templateUrl: ‘match-cell.html’
})
export class MatchCell {
@Input() name: any;
constructor(public navCtrl: NavController) {
console.log("Constructor -> MatchCell: " + this.name);
}
}

match-cell.html

THIS IS MY MATCH-CELL: {{name}}

Usage:

The HTML result is:
THIS IS MY MATCH-CELL: XYZ

but in the console, my constructor’s console log sends:
Constructor -> MatchCell: undefined

So my “name” parameter seems to be passed down and visible in my template but not in the component’s code. I have failed to find any good tutorials on creating components for RC1+ versions of Ionic. Can anyone propose a solution or refer me to a good !recent! tutorial on creating custom components in Ionic 2?

The constructor is too early. Use a later lifecycle event.

Can anyone propose a solution or refer me to a good !recent! tutorial on creating custom components in Ionic 2?

The Angular 2 book by Nate Murray et al is worth the money, in my opinion. Your question sounds like an issue of how to reason about the asynchronous nature of Angular 2. If you want to take your chances with the internet, I suggest you search on “transclusion” and “lifecycle hooks” if I understand what you’re trying to do.

Hi @rapropos, please could you show some example? I have a similar situation, I’m trying to get an Object here and also it’s null. The object holds the professional properties and then my component is to make a professional card from that object. Please any advice?

I’ve also tried to add ionViewDidLoad and ionViewDidEnter but they never fire. Perhaps because they are not considered “views”?

I’m starting to think I’m putting too much emphasis on the keywords “Ionic 2” when google searching for answers. In these cases, is it exactly the same if I search for “Angular 2” or are there nuances in Ionic 2? Do custom components follow the exact same rules?

Custom component will not have the ion- view lifecycle events.
In this case, you’ll need to use the raw angular ngOnInit, ngAfterInit hooks.

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html

5 Likes

And Mr.Hartington flies in to save the day. It works! :slight_smile: Although there is no ngAfterInit() but rather ngAfterViewInit(). I had just done the test of putting a setTimeout in the constructor (1000ms) and then console.log(this.name) and it worked so it was a question of lifecycle… but which cryptic event should I be watching for? ngOnInit() it is!

Thanks mhartington! :slight_smile:

2 Likes

Even after almost one year, mr. Hartington saved someone’s day!