0%

angular-output-decorator

The @Output decorator is used to define an output property in a component. The output property is used to emit events from the component to the parent component. The @Output decorator is used in conjunction with the EventEmitter class to emit events.

How to use the @Output decorator

  1. Create a Child component
1
2
<!--child.component.html-->
<button (click)="onClick()">Update parent name</button>
1
2
3
4
5
6
7
8
9
10
11
12
13
// child.component.t
@Component({
selector: 'app-child',
standalone: true,
// ...
})
export class ChildComponent {
@Output() updateParentName = new EventEmitter<string>();

onClick() {
this.updateParentName.emit('new name');
}
}
  1. Create a parent component
1
2
3
<!--parent.component.html-->
<p>Parent name: {{ name }}</p>
<app-child (updateParentName)="updateName($event)"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// parent.component.ts
@Component({
selector: 'app-parent',
standalone: true,
imports: [ChildComponent],
// ...
})
export class ParentComponent {
name = 'parent';

updateName(name: string) {
this.name = name;
}
}

The connection between child component and parent component is established by binding the updateParentName output property of the child component to the updateName method of the parent component.

1
2
// child.component.ts
@Output() updateParentName = new EventEmitter<string>();
1
2
<!--parent.component.html-->
<app-child (updateParentName)="updateName($event)"/>

New output api in Angular 17.3

Angular 17.3 provide a new output api to simplify the usage of @Output decorator.

1
2
3
4
5
6
7
8
9
import {output} from '@angular/core';
// ...
export class ChildComponent {
updateParentName = output<string>(); // <--- new output api

onClick() {
this.updateParentName.emit('new name');
}
}

Naming conventions

Always use camelCase output names. Avoid prefixing output names with “on”.

References:

https://angular.dev/guide/components/outputs
https://blog.angular.dev/meet-angulars-new-output-api-253a41ffa13c