Angular - 2-7 Création de composants avec le CLI et imbrication de componants
Summary
This lesson covers two methods for creating Angular components: manual creation and using the Angular CLI (ng generate component). You'll learn how to automatically generate component files including HTML, CSS, TypeScript, and spec files. The lesson demonstrates component nesting by reusing components with their selectors in other templates and shows how to verify the component structure in Chrome DevTools.
Key points
- Use 'ng generate component <name>' (or shortcut 'ng g c <name>') to create new components without manual folder setup
- Keep ng serve running in one terminal while opening a new terminal to execute CLI commands for component generation
- The CLI automatically generates component files (HTML, CSS, TypeScript, spec) and registers the component in the app module
- Components are reusable — nest components by repeating their selector in other component templates as many times as needed
- Verify component structure using Chrome DevTools inspector to see the nested component hierarchy in the DOM
- You can either delete auto-generated spec files and CSS files initially, or address them later as needed for testing and styling
FAQ
What's the difference between creating components manually vs with the CLI?
Manual creation requires setting up folder structure and files yourself. The CLI automates this by generating the folder, all necessary files (HTML, CSS, TypeScript, spec), and automatically updates the app module declaration and imports.
How do I use a generated component in another component?
Use the component's selector in another component's template. The selector is defined in the component's TypeScript file (e.g., selector: 'app-server'). You can use it as many times as needed in any template since components are reusable.
Why is it important to keep ng serve running when using CLI commands?
ng serve must continue running so your development server stays active. Open a separate terminal window for CLI commands instead of closing or interrupting the ng serve window.