Pass Values to the Custom Attribute Directive
Let’s learn how to pass data into the directive.
We'll cover the following
We learned how to create a basic attribute directive that changes the element’s appearance in the previous lesson. However, we often require the element’s appearance to work in a slightly more dynamic way. For instance, we may want the element to potentially change its appearance, but we may not want the same static values to always apply. Maybe we want to supply different values based on the actual use case. In cases like these, passing values to the directive is especially useful.
Pass values
In this lesson, we’ll continue working on the example from the previous lesson–the avatar directive. This time we want to control the size of the avatar. Previously, it worked as shown below, each time setting the width and height to 64px:
@Directive({
selector: '[appAvatar]'
})
export class AvatarDirective implements OnInit {
constructor(private elementRef: ElementRef) { }
ngOnInit() {
const size = '64px';
this.elementRef.nativeElement.style.width = size;
this.elementRef.nativeElement.style.height = size;
}
}
This time, let’s make the size
value dynamic. To do that, we want to pass the value through app.component.html
.
How do we usually pass the data between the component and its child components? We do it through inputs. Remember that most things we know from the components’ world can be used for directives, too. So, let’s use them!
We can add the input like this:
@Input() size: string;
Now, we can use its value, as shown below:
@Directive({
selector: '[appAvatar]'
})
export class AvatarDirective implements OnInit {
@Input() size: string;
constructor(private elementRef: ElementRef) { }
ngOnInit() {
this.elementRef.nativeElement.style.width = this.size;
this.elementRef.nativeElement.style.height = this.size;
}
}
Now, the directive class looks complete. We just have to provide the size value to this directive. In the previous lesson, the following was enough:
<img src="/assets/avatar.png" appAvatar>
Now, we also need to insert the attribute for the Input
property. Whenever we apply a directive to an element, it will have all of the directive public properties available such as Input
, Output
, other public methods, or other fields. All of that is available to us, and we can use it in our component.
In our case, we’ll add the binding to the size
input property:
<img src="/assets/avatar.png" appAvatar size="120px">
We provide a value of 120px
and bind it to the size property of the avatar directive. The directive can use it to initialize the element’s size, like before.
Here’s a live application for us to play around in, change values, and see how it behaves.
Get hands-on with 1400+ tech skills courses.