Binding Properties to Directives
Explore how to bind properties to custom Angular directives to dynamically manage CSS classes. Understand using the @Input decorator and TypeScript setters to accept data from components and conditionally add or remove classes on elements. Learn to enhance directives beyond static styling to create modular, reusable behavior in your Angular applications.
We'll cover the following...
We have a directive that changes the color of the text to which it’s applied. It’s not really what we were going for. Let’s modify it to add a class to an element. We want to be able to add any class we’d like.
Accepting data from the component
Luckily, we already know how to accept data from one part of the application to another. We can use the @Input() decorator to accept data from a component.
In the class.directive.ts file, we’ll update the class to the following:
In the example above, we’re importing the @Input() decorator and defining a new property, called classnames, with it. One important thing to point out is that the name of the input property must match the name of the directive. Otherwise, ...