Using $attrs and $element in components

Loading

In AngularJS 1.5+, components provide a more structured and modern way of building applications. When working with components, $attrs (Attributes Service) and $element (Element Service) are two powerful dependencies that allow you to interact with HTML attributes and DOM elements inside component controllers.


1. Understanding $attrs and $element

$attrs ($attributes service)

  • Represents HTML attributes assigned to the component.
  • Allows access to static attributes (e.g., id, class, data-* attributes).
  • Useful for checking if an attribute exists or extracting values.

$element ($element service)

  • Provides a reference to the DOM element of the component.
  • Allows direct DOM manipulation using jQuery Lite (or full jQuery if available).
  • Useful for adding/removing classes, animations, or event handling.

2. Using $attrs in an AngularJS Component

Scenario: Check if an attribute is provided and set a default if missing.

Step 1: Define the Component (myComponent)

app.component('myComponent', {
bindings: {
title: '@' // Accepts an attribute value
},
template: `<h3>{{$ctrl.title}}</h3>`,
controller: function($attrs) {
if (!$attrs.title) {
this.title = "Default Title"; // Set default if 'title' attribute is missing
}
}
});

If <my-component title="Custom Title"></my-component> is used, it displays “Custom Title”.
If <my-component></my-component> is used, it displays “Default Title”.


Using $attrs to Access Custom Attributes

app.component('myComponent', {
template: `<div>Check Console for Attributes</div>`,
controller: function($attrs) {
console.log($attrs); // Logs all attributes
}
});

Outputs all attributes assigned to <my-component> in the console.


3. Using $element for DOM Manipulation

Scenario: Change background color dynamically.

Step 1: Define the Component (colorBox)

app.component('colorBox', {
bindings: {
color: '@'
},
template: `<div class="box">Click to Change Color</div>`,
controller: function($element) {
let box = $element.find('div'); // Selects the component's div

box.on('click', function() {
let newColor = box.css('background-color') === 'rgb(255, 0, 0)' ? 'blue' : 'red';
box.css('background-color', newColor); // Change color on click
});
}
});

Step 2: Define Styles

.box {
width: 100px;
height: 100px;
background-color: red;
text-align: center;
line-height: 100px;
color: white;
cursor: pointer;
}

The box toggles between red and blue when clicked.


4. Combining $attrs and $element

Scenario: Change font size based on an attribute.

Step 1: Define the Component

app.component('textSizeComponent', {
bindings: {
size: '@'
},
template: `<p>Dynamic Font Size</p>`,
controller: function($attrs, $element) {
let fontSize = $attrs.size || '16px'; // Default size
$element.find('p').css('font-size', fontSize);
}
});

Step 2: Use the Component in HTML

<text-size-component size="24px"></text-size-component>

Displays text with a font size of 24px.
If size is missing, it defaults to 16px.


5. Key Differences Between $attrs and $element

Feature$attrs$element
What it RepresentsHTML attributesComponent’s DOM element
Data TypeObject (key-value pairs)jQuery Lite (wrapped DOM element)
When to UseRead attributes, provide defaultsModify styles, attach events
Example Use CaseCheck if an attribute existsAdd CSS classes, event listeners

6. Best Practices

Use $attrs to access and check attributes, but prefer AngularJS bindings (@, <, &).
Use $element sparingly, as direct DOM manipulation is not recommended in AngularJS.
Do not use $element for business logic; use it only for UI tweaks.

Leave a Reply

Your email address will not be published. Required fields are marked *