How to Create a Component in Angular: Simple Guide
To create a component in Angular, use the Angular CLI command
ng generate component component-name. This command creates the component files and updates the module automatically, allowing you to use the component in your app.Syntax
The basic syntax to create a component using Angular CLI is:
ng generate component <component-name>orng g c <component-name>- This creates four files:
.ts(TypeScript logic),.html(template),.css(styles), and.spec.ts(tests). - The component is automatically declared in the nearest Angular module.
bash
ng generate component my-new-componentExample
This example shows how to create a simple Angular component named hello-world and use it in the app.
typescript/html
/* Command to create component */ ng generate component hello-world /* hello-world.component.ts */ import { Component } from '@angular/core'; @Component({ selector: 'app-hello-world', templateUrl: './hello-world.component.html', styleUrls: ['./hello-world.component.css'] }) export class HelloWorldComponent { message = 'Hello, Angular!'; } /* hello-world.component.html */ <p>{{ message }}</p> /* app.component.html (to use the new component) */ <app-hello-world></app-hello-world>
Output
Hello, Angular!
Common Pitfalls
Common mistakes when creating Angular components include:
- Not running the command inside an Angular project folder.
- Forgetting to use the component's selector tag in the template.
- Manually creating files without updating the module, causing the component not to work.
- Using invalid characters or spaces in the component name.
bash
/* Wrong: Creating component files manually without module update */ // Files created but component not declared in module /* Right: Use Angular CLI to auto-update module */ ng generate component valid-name
Quick Reference
Tips for creating Angular components:
- Use Angular CLI for easy and correct setup.
- Component names should be kebab-case (lowercase with dashes).
- The selector is the HTML tag to use the component.
- Component files include logic (
.ts), template (.html), styles (.css), and tests (.spec.ts).
Key Takeaways
Use Angular CLI command
ng generate component to create components easily.Component files include TypeScript, HTML template, CSS styles, and tests.
The component selector is used as an HTML tag to display the component.
Always create components inside an Angular project folder to avoid errors.
Avoid manual file creation to ensure the module updates automatically.