Angular Components

Chapter 3: Angular Components

  • Understanding components in Angular:

Components are the building blocks of an Angular application. They are responsible for handling the logic and rendering the UI for a specific part of the application. To create a component, you need to define a TypeScript class, an HTML template, and optional CSS styles.

Create a new component by running the following command in the terminal:

ng generate component component-name

This will create the necessary files for the component, including a TypeScript class, an HTML template, and a CSS file. You can find these files in the corresponding component folder.

  1. Creating and using components:

To create a component, you define a TypeScript class with the @Component decorator. The decorator provides metadata for the component, such as the selector (used to identify the component in HTML), template URL (the path to the HTML template file), and styles (the CSS styles for the component).

In the TypeScript class of your component, you can define properties, methods, and lifecycle hooks. For example:

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  name: string = 'John';

  greet() {
    console.log('Hello, ' + this.name);
  }
}

In the HTML template, you can use the component’s properties and methods:

<p>Hello, {{ name }}</p>
<button (click)="greet()">Greet</button>
  1. Component communication:

Component communication allows components to interact and share data with each other. There are three main ways to achieve this: input properties, output properties with event emitters, and services.

To pass data from a parent component to a child component, you can use input properties. In the parent component, you define the property and bind it to a value:

<app-child [name]="parentName"></app-child>

In the child component, you use the @Input decorator to declare the input property:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Input() name: string;
}

To emit events from a child component to a parent component, you can use output properties and event emitters. In the child component, you define the output property and emit an event:

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Output() clicked = new EventEmitter<void>();

  handleClick() {
    this.clicked.emit();
  }
}

In the parent component, you can handle the emitted event:

<app-child (clicked)="handleClick()"></app-child>