Angular Component
In Angular, a component is a fundamental building block of an application's user interface (UI). It encapsulates the behavior, structure, and styling of a part of the UI, making it reusable, modular, and easy to maintain. Components are typically organized hierarchically, with parent and child components forming a tree-like structure.
Creating a Component
To create a component in Angular, you need to follow these steps:
- Use the Angular CLI: The Angular CLI (Command Line Interface) provides a convenient way to generate Angular components. Open your terminal or command prompt and run the following command:
- Manually Create a Component: If you prefer to create components manually, you need to create four files for each component:
- TypeScript file (.ts): Contains the component class and logic.
- HTML file (.html): Defines the component's template.
- CSS/SCSS file (.css or .scss): Contains the component's styles (optional).
- Spec file (.spec.ts): Contains unit tests for the component (optional).
html
ng generate component my-component
This command will create a new folder named my-component in your project directory, containing the files necessary for the component.
Example of a Component
Let's create a simple component called my-component
- Using Angular CLI
- Manually
syntax
ng generate component my-component
typescript
// my-component.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
// Component logic goes here
}
typescript
<!-- my-component.component.html -->
<div>
<h2>Hello, I'm a custom component!</h2>
</div>