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
...