In this section, we will delve into the core building blocks of any Angular application: components. Components are the fundamental units of an Angular application, encapsulating the logic, template, and styles that define a part of the user interface.

Key Concepts

  1. Component Definition: A component in Angular is defined using a TypeScript class decorated with @Component.
  2. Component Metadata: The @Component decorator provides metadata about the component, such as its selector, template, and styles.
  3. Component Lifecycle: Components have a lifecycle managed by Angular, with hooks that allow you to tap into key moments of a component's existence.

Creating a Component

Step-by-Step Guide

  1. Generate a Component: Use Angular CLI to generate a new component.

    ng generate component my-component
    

    This command creates a new folder named my-component with the following files:

    • my-component.component.ts: The TypeScript file containing the component class.
    • my-component.component.html: The HTML template for the component.
    • my-component.component.css: The CSS styles for the component.
    • my-component.component.spec.ts: The test file for the component.
  2. Component Class: The generated my-component.component.ts file will look like this:

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.css']
    })
    export class MyComponent implements OnInit {
      constructor() { }
    
      ngOnInit(): void {
      }
    }
    
    • @Component: Decorator that marks the class as an Angular component and provides metadata.
    • selector: The HTML tag that represents the component.
    • templateUrl: Path to the HTML template file.
    • styleUrls: Path to the CSS file(s).
  3. Template: The my-component.component.html file contains the HTML structure of the component.

    <p>
      my-component works!
    </p>
    
  4. Styles: The my-component.component.css file contains the styles specific to the component.

    p {
      color: blue;
    }
    

Practical Example

Let's create a simple component that displays a list of items.

  1. Generate the Component:

    ng generate component item-list
    
  2. Modify the Component Class (item-list.component.ts):

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-item-list',
      templateUrl: './item-list.component.html',
      styleUrls: ['./item-list.component.css']
    })
    export class ItemListComponent implements OnInit {
      items: string[] = ['Item 1', 'Item 2', 'Item 3'];
    
      constructor() { }
    
      ngOnInit(): void {
      }
    }
    
  3. Update the Template (item-list.component.html):

    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    
  4. Add Some Styles (item-list.component.css):

    ul {
      list-style-type: none;
      padding: 0;
    }
    
    li {
      background-color: #f0f0f0;
      margin: 5px 0;
      padding: 10px;
      border-radius: 4px;
    }
    

Using the Component

To use the ItemListComponent in your application, include its selector in the template of another component, such as app.component.html:

<app-item-list></app-item-list>

Practical Exercises

Exercise 1: Create a User Profile Component

  1. Generate a new component named user-profile.
  2. Add properties for name, age, and email in the component class.
  3. Display these properties in the component template.
  4. Style the template to make it visually appealing.

Solution:

  1. Generate the component:

    ng generate component user-profile
    
  2. Update the component class (user-profile.component.ts):

    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-user-profile',
      templateUrl: './user-profile.component.html',
      styleUrls: ['./user-profile.component.css']
    })
    export class UserProfileComponent implements OnInit {
      name: string = 'John Doe';
      age: number = 30;
      email: string = '[email protected]';
    
      constructor() { }
    
      ngOnInit(): void {
      }
    }
    
  3. Update the template (user-profile.component.html):

    <div class="profile">
      <h2>{{ name }}</h2>
      <p>Age: {{ age }}</p>
      <p>Email: {{ email }}</p>
    </div>
    
  4. Add styles (user-profile.component.css):

    .profile {
      border: 1px solid #ccc;
      padding: 20px;
      border-radius: 8px;
      max-width: 300px;
      margin: 20px auto;
      text-align: center;
    }
    
    h2 {
      margin-bottom: 10px;
    }
    
    p {
      margin: 5px 0;
    }
    

Common Mistakes and Tips

  • Selector Naming: Ensure the selector name is unique to avoid conflicts with other components.
  • Template and Style Paths: Verify that the paths to the template and style files are correct.
  • Lifecycle Hooks: Utilize lifecycle hooks like ngOnInit to perform initialization logic.

Conclusion

In this section, we learned how to create and use components in Angular. We covered the basics of component definition, metadata, and lifecycle. We also walked through a practical example and provided an exercise to reinforce the concepts. In the next section, we will explore component templates in more detail.

© Copyright 2024. All rights reserved