Attribute Binding (attr) in Angular
⭐ What Is Attribute Binding (attr) in Angular?
Attribute binding in Angular lets you set HTML attributes dynamically using data from your component.
Syntax:
Example:
You use attr. because not all HTML attributes map to DOM properties.
🎯 Why Use Attribute Binding?
Use attr. when:
- The attribute doesn’t have a direct property in DOM
- You want to conditionally add or remove an attribute
- You are working with SVG, ARIA, or table attributes like colspan, rowspan
🧩 Example 1: Dynamic colspan
TS:
Output → <td colspan="3">
🧩 Example 2: Adding ARIA attributes
TS:
🧩 Example 3: Conditional Attributes
If value is null or undefined, Angular removes the attribute.
TS:
Output → <button disabled></button>
🧩 Example 4: Setting Custom Attributes
Useful when interacting with libraries or data attributes:
TS:
Output → <div data-id="123"></div>
🧩 Example 5: SVG Attributes
DOM property binding doesn’t work with many SVG attributes, but attr works:
TS:
🧩 Example 6: Setting tabindex dynamically
🔍 Attribute Binding vs Property Binding
| Feature | Property Binding [prop] |
Attribute Binding attr. |
|---|---|---|
| Applies to | DOM properties | HTML attributes |
| Updates | Real-time | Only HTML attribute |
| Used for | Most bindings | Special/unsupported attributes |
| Example | [disabled]=true |
[attr.colspan]=3 |
Use property binding when possible; use attr. when required.
🎉 One-Line Summary
👉 Use [attr.x] when you need to set an actual HTML attribute that Angular cannot handle via normal property binding.
