Attribute Directives in Angular
Introduction
Welcome to the lesson on attribute directives in Angular! In this lesson, we'll explore how attribute directives can enhance the appearance and behavior of DOM elements in your Angular applications. Attribute directives are distinct from structural directives, as they modify existing elements rather than adding or removing them. Understanding this distinction is crucial as we dive into the world of Angular directives. Let's get started! 🌟
Exploring Built-in Attribute Directives
Angular provides several built-in attribute directives that allow you to dynamically alter the styles and classes of elements. Two commonly used directives are ngClass and ngStyle. These directives enable you to bind dynamic values to an element's class and style properties, respectively.
In the examples above, ngClass is used to conditionally apply the 'active' or 'disabled' class based on the isActive property. Similarly, ngStyle dynamically sets the text color and font size based on the textColor and fontSize properties. These directives provide a powerful way to control the presentation of your elements based on component data.
Creating a Custom Attribute Directive
Now, let's create a custom attribute directive to understand how directives work under the hood. We'll build a directive that changes the background color of an element when hovered over.
In this directive, we use @Directive to define a new directive with the selector appHoverHighlight. The Renderer2 service is used to safely manipulate the DOM, setting the background color to yellow on mouse enter and reverting it to white on mouse leave. This example demonstrates how custom attribute directives can enhance user interaction.
