Angular - 3.5 creation of components

With the project configured and Bootstrap wired in, we now create every component identified during the planning step. The exercise: try it by yourself first. Sketch the folders, decide whether each component lives next to AppComponent or nested by feature, and create at least one component manually — without the CLI — to make sure the manual workflow sinks in.

Walkthrough

For the header we create a header folder inside app/ and a header.component.ts by hand. A component is just a TypeScript class decorated with @Component imported from @angular/core. The decorator receives a selector (app-header), a templateUrl pointing to ./header.component.html and we create that file with a quick <h1> placeholder.

Because the component was created manually, Angular does not know about it yet. We must register it in app.module.ts: add the import at the top, then the class to the declarations array. Forgetting this step gives a console error app-header is not a known element — a classic trap when you skip the CLI.

For every other component we lean on the CLI to go faster. The ng generate component command (alias ng g c) lays out the folder, the four files and the module registration in one shot. Adding --skip-tests=true avoids creating the spec file we do not need yet. To nest components by feature, prefix the name with a folder path, otherwise the CLI creates the component at the root of app/:

  • ng g c recipes --skip-tests=true — top-level recipes feature.
  • ng g c recipes/recipe-list --skip-tests=true — recipe list inside the recipes feature.
  • ng g c recipes/recipe-detail --skip-tests=true — recipe detail next to the list.
  • ng g c recipes/recipe-list/recipe-item --skip-tests=true — single item nested in the list.
  • ng g c shopping-list --skip-tests=true + shopping-list/shopping-edit — shopping list and its edit area.

Once every component is generated, Angular registers them automatically and the project tree faithfully mirrors the plan: recipes and shopping list are independent feature folders, each with their children. Created manually or via the CLI, components are now ready to be wired together in the next lesson where we will use them inside app.component.html.