# Event Handling

## Binding Events

Allows HTML DOM element events to be bound to component functions or variables can be set. Event binding is done using parenthesis and can be used for events like click, keyUp, keyDown, mouseover, etc.

![](https://3208804520-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LHxcOLKU4vpIQfXJm9H%2F-Ll2MKVTu6yOp2S5XSUI%2F-Ll2MfaILItGQN0u9RM-%2Fevent_handling.jpg?alt=media\&token=3407ad8c-7390-4942-bdec-81970c4eb8eb)

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-6dot5?file=src%2Fapp%2Fmy%2Fmy.component.ts&view=editor>" %}

## Raising Custom Events

Child components can raise custom events to parent components to allow them to respond appropriately using the `Output()` decorator.

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-6dot5?file=src%2Fapp%2Fchild%2Fchild.component.ts&view=editor>" %}

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-6dot5?file=src%2Fapp%2Fparent%2Fparent.component.ts&view=editor>" %}

{% hint style="info" %}
Pro Tip: @Input() and @Output() are the building blocks for component patterns like container/presenter (smart/dumb) components.
{% endhint %}

## Two Way Data Binding

Two way data binding allows an input, select, etc to be bound to a component's variable. As the value changes on the HTML element, the variable value is updated. The syntax looks like `[(ngModel)]="variable_name"`

{% code title="person.component.ts" %}

```typescript
import { Person } from './models/person';

@Component({
    selector: 'app-person',
    template: `name: <input [(ngModel)]="person.name" />
    <p>Your name is: {{person.name}}</p>
    `
})
export class PersonComponent {
    person: Person = {name: "Bob"};
}
```

{% endcode %}

{% hint style="warning" %}
Warning - two way data binding can cause performance issues and could be problematic in larger enterprise applications.
{% endhint %}

## Summary <a href="#summary" id="summary"></a>

* Binding events
* Raising custom events
* Two way data binding
