[SOLVED] Component selector always needed?


#1

I just created a new page using “ionic g page …” and I noticed that typescript class was generated with a @Component selector declaration per default.

@Component({
    selector: 'page-todo',
    templateUrl: 'todo.html'
})

Usually, when I wrote pages which I know I’m not gonna include in other components (let’s say root pages or full pages), I didn’t add the selector attribute. Most of my pages look like

@Component({
    templateUrl: 'todo.html'
})

Is that a bad practice? Is it better to always specify selector?


#2

Seems like Ionic uses the selector for styling. In your example you would have a todo.scss file with

page-todo {
  // add your styles here
}

If you do have a selector your component will be rendered as e.g.

<page-todo>
  <!-- rendered template here -->
</page-todo>

so that page-todo element can be used for applying css rules. If you don’t specify a selector Angular will generate something like

<ng-component>
  <!-- rendered template here -->
</ng-component>

So yeah it’s better to always specify a selector.


#3

Thx for the answer, make sense. In that way I don’t have to set an id on each pages for my specific styles.


#4

Is there any way to use @Input here? I’m having problems doing that.


#5

I’m not following you. What does @Input have to do with selector?


#6

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"></child-component>

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!


#7

Why don’t you post a separate question?


#8

Exactly what I was going to do if you didn’t know the answer.