AngularJs 2 Series: Binding The Host Element With @HostBinding
Introduction
In one of the previous article Build Your Own Directive, I showed you how to build or develop a custom highlight attribute that highlights the text background with yellow. We made use of Renderer
service to render an element with the background style color to yellow. The element reference (which contained the text) was obtained using ElementRef
type. We bound the style.background
attribute of that element with the value of yellow using the setElementStyle
method of the Renderer
service. In this article I will use the same Typescript class and show you the alternate way to highlight the hosting element. We will use something called as @HostBinding
decorator or meta data.
Using @HostBinding
The @HostBinding
decorator can be used to bind a value to the attribute of the hosting element, in our case, the element hosting the highlight
directive. Let’s look at the code that makes use of @HostBinding
decorator.
import { Directive, HostBinding } from '@angular/core'; @Directive({ selector: '[highlight]' }) export class HighlightDirective { private color = "yellow"; @HostBinding('style.backgroundColor') get getColor() { return this.color; } constructor() { } }
The above is the same directive class with the highlight attribute. The only difference is here now we are rendering the element color to yellow using @HostBinding
decorator instead of the Renderer
service. Let’s walk through the code. First we define a property named color
and set its default value to yellow. Next we define the @HostBinding
decorator which is part of core Angular package. The said decorator accepts the name of the attribute to which we want to bind the value in the hosting element. The attribute in this case will be style.background
because we need to set the background color. The get
is a built-in concept of Typescript which acts like getter function to the property. The getColor()
method acts as a property to the get ‘getter’ which simply returns the value of the color
property.
The
getColor()
method name has nothing to do with thecolor
property that we have defined. The method name can be anything and it should return the value which is eventually bound to the hosting element.
Upon running the application, you should see the text with highlighted color as yellow.
Reference: | AngularJs 2 Series: Binding The Host Element With @HostBinding from our WCG partner Rajeev Hathi at the TECH ORGAN blog. |
HI, IT VERY USEFULL FOR ME, THANKS TO WEBCODGEEKS