loading...
Cover image for Angular @Output Hooks

Angular @Output Hooks

jwp profile image John Peters ・2 min read

When we see the word 'output' we know the implicit meaning is something that streams from something to something else. The direction being outward from the source to the target. We are easily able to identify the source as some type of EventEmitter in this example.

@Component
export class myclass{
@Output() something:EventEmitter<Person>
}

The @ characters in Angular are decorators. The best way to think of Decorators is that they deal with Aspects which are hidden. They are a Cross Cutting Concern.

Angular has defined a number of decorators it must have to make Angular work.

Output Event Emitter

// bad name
@Output() something:EventEmitter<Person>
// good name!
// always append Event to the name 
// and describe it well
@Output() NewPersonEvent:EventEmitter<Person>

Create the Hook

//code for the consumer of @output shown above
//this is the hook, it hooks the event to our typescript code.

<my-class [NewPersonEvent]='onNewPerson(person)' </my-class>

Event Handler


@Component
export class myOtherClass{
onNewPerson(person){
  // here, we see the new person object
  // we are not forced to type person 
  // e.g. person:Person 
  // but without the typing,
  // we can not see the properties
  // using autocompletion. 
  }
}

This pattern is at least 50 years old. It's traditionally known as an EventHandler. Event Handlers always have had to be hooked up to the event before seeing anything. Today's Web Browsers all use events almost exclusively for passing information around. Events were the very first observer pattern.

In .NET, registering an event-handler can interfere with garbage collection. The garbage collect will not free up memory for anything still hooked, even if the code that hooked it is no longer there!

But there doesn't seem to be the same garbage collection problem in Angular.

JWP 2020

Discussion

pic
Editor guide