Angular - 2-7 Creating components with the CLI and nesting components
Up until now we created our components by hand, but the Angular CLI offers a much faster alternative. While the ng serve window keeps running, open a second terminal in the same project and use the generate command to scaffold a new component. Say we want a unique-server component nested inside another component — the CLI can lay out the folder, the four files and even register the class in the module automatically.
Generating and nesting components
The full command is ng generate component server, with a shorter alias ng g c server. Both produce a new server folder containing the HTML, CSS, TypeScript and spec files. The spec file is for unit testing and can be deleted for now; we will cover testing later. The CLI also updates app.module.ts by adding the import and the declaration, but it is always worth double-checking that it really did so.
ng generate component <name>— full command.ng g c <name>— short alias used most of the time.ng g c <path>/<name>— generate the component inside a subfolder.
Inside the new server.component.html we can replace the default paragraph with a small message — for example <p>A server</p> — and even duplicate it twice to show that components are reusable: the same selector can be dropped multiple times and Angular will render the template once per occurrence. Then in app.component.html we just swap the old selector for the new one to nest the freshly generated component inside the root component.
Saving the file triggers a recompile and the browser shows the same output as before. If we open the Chrome DevTools and inspect the page, we can clearly see the new component element wrapping the two repeated app-server instances. In a few minutes we learned three things: how to create components either manually or via the CLI, how to nest them by using selectors inside other templates, and how easily we can reuse the same component many times. Next we will look at how to customise templates and styles for each component.