Binding Properties to Directives
Learn how to bind properties to directives to make them more dynamic.
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:
Press + to interact
import { Directive, ElementRef, Input } from '@angular/core';@Directive({selector: '[appClass]'})export class ClassDirective {@Input('appClass') classnames: string;constructor(private el: ElementRef) {this.el.nativeElement.classList.add(this.classnames);}}
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 ...
Get hands-on with 1400+ tech skills courses.