ThisCalculator

Everyday

Angular Component Outputs: Sending Events to Parent

Updated · Standard formula, shown below

Yes, Angular component outputs send events and data to a parent component. You declare an @Output() property (usually an EventEmitter) in the child, emit values with .emit(), and the parent listens via event binding (eventName)="handler($event)" in its template. This is the standard, recommended way for a child to communicate upward.

Background: Why Outputs Exist

Angular components are designed to be reusable and encapsulated. Data flows down through inputs (@Input()) and flows up through outputs (@Output()). This one-way data flow keeps the component tree predictable: a child never directly modifies parent state; instead it notifies the parent, and the parent decides what to do. This pattern is often called “smart/dumb” or “container/presentational” components, where the parent holds the logic and the child simply emits events about user actions.

How Outputs Work: The Mechanics

An @Output() property must be an EventEmitter (though technically any Observable works, EventEmitter is the conventional choice). The child calls .emit(value) to send a payload. The parent template binds to the event name with parentheses: (childEvent)="onChildEvent($event)". The $event variable holds whatever value was emitted.

Here is a minimal example:

// child.component.ts
@Component({...})
export class ChildComponent {
  @Output() save = new EventEmitter<string>();
  submit() {
    this.save.emit('form data');
  }
}

// parent.component.html
<app-child (save)="handleSave($event)"></app-child>

// parent.component.ts
handleSave(data: string) {
  console.log(data); // 'form data'
}

The event name in the template must match the @Output() property name exactly. You can alias it with @Output('aliasName') if you want a different public name.

When to Use Outputs vs. Other Methods

Outputs are the right choice when you have a direct parent-child relationship and the child needs to notify the parent of something. Use them for:

  • User actions (button clicks, form submits, item selection)
  • Child lifecycle events (loaded, destroyed, resized)
  • Requests for parent action (“load more”, “open modal”)

If you need to communicate between siblings or unrelated components, outputs are not ideal. Instead consider a shared service with a subject, or a state management library. If the communication is frequent and complex, a service often leads to cleaner code than a long chain of outputs.

Common Mistakes and Pitfalls

Several issues trip up developers new to outputs:

  • Forgetting to emit: The output only fires when .emit() is called. If you forget, the parent never knows.
  • Using the wrong event name: The template binding must match the property name. A typo silently breaks the binding.
  • Emitting before parent subscribes: In Angular, the parent binding is set up before the child’s ngOnInit, so emitting in the constructor or early lifecycle is fine. But emitting in a service that runs before the component is created will be missed.
  • Mutating emitted objects: If you emit an object and then change it after emitting, the parent sees the mutated object. Emit a copy if you need to preserve a snapshot.
  • Using outputs for every interaction: Overusing outputs can lead to “event spaghetti”. Sometimes a simple callback input or a service is cleaner.

Outputs with Async and Observables

While EventEmitter is an Observable, you can also use a plain Subject or BehaviorSubject as an output. This is useful when you want to expose a stream of events that the parent can subscribe to imperatively, or when you want to combine with RxJS operators. However, the template binding syntax remains the same: (eventName)="handler($event)" works with any observable that emits values.

For example, a child might expose a @Output() that is a Subject:

@Output() changes = new Subject<number>();
// later
this.changes.next(42);

This works, but EventEmitter is the idiomatic choice for component outputs because it is specifically designed for that purpose and is compatible with Angular’s change detection.

Outputs and Change Detection

When a child emits an event, Angular’s change detection runs automatically for the parent and its subtree (unless you have ChangeDetectionStrategy.OnPush on the parent). This means the parent’s template will update if it depends on the emitted data. However, if the parent uses OnPush, the event binding still triggers a check for that component, so it will update. The event itself is a signal that triggers change detection, which is why outputs are a reliable way to update parent state.

Alternatives to Outputs

There are several alternatives, each with trade-offs:

  • Callback inputs: Pass a function as an @Input() and call it. This is simpler but less idiomatic in Angular.
  • Shared service: A service with a subject can be injected into both components. This decouples them but adds indirection.
  • State management (NgRx, Akita): For large apps, a central store can handle complex communication.
  • Template reference variables: The parent can access child methods directly via @ViewChild, but this is more imperative and less reactive.

Outputs are usually the best starting point because they keep the component API explicit and follow Angular’s conventions.

Frequently Asked Questions

Can I emit multiple values from one output?

Yes, you can call .emit() multiple times on the same output. Each call triggers the parent’s handler. If you need to send different types of events, consider using a discriminated union or separate outputs for clarity.

What is the difference between @Output and @Input?

@Input() passes data from parent to child, setting a property on the child. @Output() sends events from child to parent, allowing the parent to react. Inputs are for data, outputs are for actions.

How do I pass the event object from a DOM event to an output?

In the child template, you can catch a DOM event and re-emit it: <button (click)="onClick($event)">Click</button> and then in the class, onClick(event: MouseEvent) { this.myOutput.emit(event); }. This lets the parent receive the original DOM event.

Can an output be optional?

Yes, you can make an output optional by not initializing it or by checking if it has subscribers. However, the parent binding is always set up if present. If no parent binds to it, calling .emit() is safe and does nothing.

Is it possible to have an output with the same name as a DOM event?

Yes, but it can be confusing. For example, a component with an @Output() click would override the native click event on that element. Prefer a more specific name like itemClick to avoid ambiguity.

How do I test an output?

In a unit test, you can spy on the emit method or subscribe to the output and then trigger the child method. For example: spyOn(component.myOutput, 'emit'); component.submit(); expect(component.myOutput.emit).toHaveBeenCalledWith('data');.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.