DEV Community

Benjamin RICHARD
Benjamin RICHARD

Posted on

Yet another Angular article, part 5 : output

Image description

In communication between component you have to define inputs, describes in previous articles, and outputs.

If inputs are the solution to give information from parent, to children, then outputs allows children to send information to their parents.

With Angular, outputs are declared in chilren using a signal like this :

public myOutput = output<string>();
public setMyOutput = (myOutput: string) => this.myOutput.emit(myOutput)
Enter fullscreen mode Exit fullscreen mode

And parent component can listen to output with this syntax :

@Component({
  ...
  template: `<childrenComponent (myOutput)="setUsername($event)"/>`
})
export class ParentComponent {
  setUsername(username: string) {
    ...
  }
}
Enter fullscreen mode Exit fullscreen mode

So, output MUST be public. And to listen to output, you MUST use parenthesis, AND use the standard $event variable that is the keyword used everytime in template to bind event.

That’s all !

But…

You can do something else. Here you have to manually ‘emit’ the new value. In fact, the previous output syntax (before v18) was really similar to EventEmitter. So, it was possible to use Observable as Output like this :

public @Output() myOutput$ = toObservable(this.myOutput);
Enter fullscreen mode Exit fullscreen mode

Each time the Observable changes, an event is emitted. The source of the Observable can be a Subject, or like in my sample, an Observable based on a signal, using toObservable operator.

That’s all for output parts.

Have a nice 🌧️ day

[note] all articles use command from Angular v19*

[demo] a sample project is available on StackBlitz

Top comments (0)