Steps to create working custom components

These are very totally opposite-of-dumb questions, that expose the fact (IMHO) that there are some parts of the typical Ionic development experience that cross the line from being useful to being “too cute for their own good”.

So some guidelines I have found useful:

  • ground yourself in Angular. go through the Tour of Heroes. yes, it seems long and daunting at first, but it really will contain the answers to 90% of the questions you are going to have.
  • maybe eventually you will find the generators useful. I’ve been working with Ionic for almost 4 years, and I’m yet to hit that point, though. I think there is real value in organizing your project and making the files yourself, because you understand how the pieces fit together and learn to recognize common situations where they aren’t, such as the one you’ve hit here.
  • which leads me to lazy loading. I think it causes way more problems than it solves, especially for non-colossal apps and people who are just starting out. so this is how I would solve your current problem:

A. Generate a new project with the “blank” starter instead of the “tabs” one.
B. Delete every file under src/app/ with module in its name, except for app.module.ts.
C. Replace the import of AppRoutingModule in app.module.ts with:

RouterModule.forRoot([
      {path: '', redirectTo: 'home', pathMatch: 'full'},
      {path: 'home', component: HomePage}
    ])

D. Add HomePage to the declarations stanza of AppModule while you’re there
E. Run ionic serve and make sure the world is your oyster.
F. Stop the ionic serve process
G. Now make a span1 directory and three files in it:

span1.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-span1',
  templateUrl: './span1.component.html',
  styleUrls: ['./span1.component.scss'],
})
export class Span1Component {}

span1.component.scss

empty for now, but must exist

span1.component.html

<span>hello world</span>

H. Put a <my-span></my-span> in your app.component.html somewhere
I. Add Span1Component to the declarations stanza of your app module, right next to HomePage.
J. Run ionic serve again and hopefully hello world will appear as well

If you decide instead that you really really want the lazy loading stuff, you are going to have to add MySpan1ComponentModule to the imports stanza of Tab1PageModule. Then you’re going to have to remember to do something similar absolutely every single time you want to use component X in component Y. That should fix things within your existing project, though.

2 Likes