@HostBinding in Angular
In Angular, @HostBinding is a bridge that connects your directive's TypeScript logic to the properties of the HTML element it sits on. It can target four main categories: Classes, Styles, Properties, and Attributes.
Here is a comprehensive list of the most common and probable bindings you will use.
1. CSS Class Bindings
This is the most frequent use case. You can toggle a single class or manage all classes at once.
- Single Class (Boolean): Adds the class if the value is
true.
- Multiple Classes (String): Replaces the entire
classattribute.
2. CSS Style Bindings
You can bind to specific CSS properties. Angular also allows you to specify units (like px, %, em) directly in the binding.
- Standard Style:
- Style with Units: (Very useful for dynamic layouts)
3. Native DOM Properties
These target the internal properties of the DOM element. Unlike attributes, these affect the "live" state of the element.
- Common Properties:
- TypeScript
- Content Properties:
4. HTML Attributes
Some values (like ARIA labels for accessibility or custom data attributes) are not properties but attributes. You must use the attr. prefix for these.
- Accessibility (ARIA):
- Custom Data Attributes:
- Media Attributes:
Summary Table
| Binding Type | Syntax Example | Common Use Case |
| Boolean Class | class.some-class | Toggling active, loading, or error states. |
| Property | disabled | Enabling/disabling buttons or inputs. |
| Unit Style | style.height.px | Dynamic heights for progress bars or sidebars. |
| ARIA Attr | attr.aria-hidden | Managing accessibility for screen readers. |
| Content | innerText | Dynamically changing labels (like your Copyright example). |