Host element
To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements.
A component can interact with its host DOM element in the following ways:
- It can listen to its events
- It can update its properties
- It can invoke methods on it
The component, for instance, listens to the input event using hostListeners
, trims the value, and then stores it in a field. Angular will sync up the stored value with the DOM.
@Directive({ selector: '[trimmed-input]' }) class TrimmedInput { @HostBinding() value: string; @HostListener("input", "$event.target.value") onChange(updatedValue: string) { this.value = updatedValue.trim(); } }
Note, I don't actually interact with the DOM directly. Angular aims to provide a higher-level API, so the native platform, the DOM, will just reflect the state of the Angular application. This is useful for a couple of reasons:
- It makes components easier to refactor.
- It...