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.

Raising Custom Events

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

Pro Tip: @Input() and @Output() are the building blocks for component patterns like container/presenter (smart/dumb) components.

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"

person.component.ts
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"};
}

Warning - two way data binding can cause performance issues and could be problematic in larger enterprise applications.

Summary

  • Binding events

  • Raising custom events

  • Two way data binding