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:

  1. 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:
  2. 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.

  3. 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).

Example of a Component

Let's create a simple component called my-component

  1. Using Angular CLI
  2. syntax
    ng generate component my-component
  3. Manually
  4. 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>
Next Article ❯