Git Tutorial

Angular @Output() Decorator

Understanding @Output Angular

In Angular, @Output is used to create custom events that enable child-to-parent component communication. It is typically paired with EventEmitter to allow the child component to send data to the parent component when an event occurs.

How @Output works

  1. Child Component: Declares an @Output property, which is an instance of EventEmitter.
  2. Parent Component: Listens to the custom event emitted by the child component.

Simple Counter

1. Create a Child Component

//ng generate component Counter

// counter.component.ts
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="increment()">Increment</button>
    <button (click)="decrement()">Decrement</button>
  `,
})
export class CounterComponent {
  @Output() valueChanged = new EventEmitter<number>();
  private counter = 0;

  increment() {
    this.counter++;
    this.valueChanged.emit(this.counter);
  }

  decrement() {
    this.counter--;
    this.valueChanged.emit(this.counter);
  }
}

Use the Child Component in the Parent Component

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Counter Value: {{ counterValue }}</h1>
    <app-counter (valueChanged)="onValueChange($event)"></app-counter>
  `,
})
export class AppComponent {
  counterValue = 0;

  onValueChange(value: number) {
    this.counterValue = value;
  }
}

Emit Multiple Events

You can declare multiple @Output properties to emit different events.

// toggle.component.ts
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-toggle',
  template: `
    <button (click)="toggle()">Toggle</button>
  `,
})
export class ToggleComponent {
  @Output() turnedOn = new EventEmitter<void>();
  @Output() turnedOff = new EventEmitter<void>();

  private isOn = false;

  toggle() {
    this.isOn = !this.isOn;
    this.isOn ? this.turnedOn.emit() : this.turnedOff.emit();
  }
}
// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <app-toggle (turnedOn)="onTurnedOn()" (turnedOff)="onTurnedOff()"></app-toggle>
    <p>{{ message }}</p>
  `,
})
export class AppComponent {
  message = 'The switch is off.';

  onTurnedOn() {
    this.message = 'The switch is on!';
  }

  onTurnedOff() {
    this.message = 'The switch is off.';
  }
}

Using @Output, you can effectively build highly interactive and dynamic applications by enabling seamless child-to-parent communication.

1 thought on “Angular @Output() Decorator”

  1. Pingback: What Is Angular - Tech Mentor

Leave a Comment

Your email address will not be published. Required fields are marked *