{"id":600,"date":"2016-11-01T09:05:00","date_gmt":"2016-11-01T09:05:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=600"},"modified":"2025-02-21T09:34:29","modified_gmt":"2025-02-21T09:34:29","slug":"custom-attribute-directive-in-angular","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/custom-attribute-directive-in-angular","title":{"rendered":"How To Create Custom Attribute Directive in Angular"},"content":{"rendered":"\n<p>In this post, we will learn how to create Attribute Directives in Angular. So let\u2019s say we want to change the background color of an element; in that case we would apply the attribute directive to the element.<\/p>\n\n\n\n<p>Attribute Directives are used to change the behavior, appearance or look of an element on a user input or via data from the service. Essentially, there are three types of directives in Angular 2:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Component<\/li>\n\n\n\n<li>Structural directives<\/li>\n\n\n\n<li>Attribute directives<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"create-first-attribute-directive\">Create first Attribute directive<\/h2>\n\n\n\n<p>Let\u2019s start with creating the Attribute Directive. To do this, we need to create a class and decorate it with <b>@directive<\/b> decorators. A simple attribute directive to change the color of an element can be created as shown in the next listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import\u00a0{\u00a0Directive,\u00a0ElementRef,\u00a0Renderer\u00a0}\u00a0from\u00a0'@angular\/core';\n \n@Directive({\n\u00a0\u00a0\u00a0\u00a0selector:\u00a0'[chcolor]'\n})\nexport\u00a0class\u00a0ChangeColorDirective\u00a0{\n \n\u00a0\u00a0\u00a0\u00a0constructor(private\u00a0el:\u00a0ElementRef,\u00a0private\u00a0render:\u00a0Renderer)\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.changecolor('red');\n\u00a0\u00a0\u00a0\u00a0}\n \n\u00a0\u00a0\u00a0\u00a0private\u00a0changecolor(color:\u00a0string)\u00a0{\n \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.render.setElementStyle(this.el.nativeElement,\u00a0'color',\u00a0color);\n\u00a0\u00a0\u00a0\u00a0}\n}<\/pre>\n\n\n\n<p>While we\u2019re creating an attribute directive to change the color of the element, keep in mind that we don\u2019t need to create a new attribute directive to just change the color; simple colors can be changed by using property binding. However, the attribute directive we created will change color of an element in this example. There are few important points to remember:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Import required modules like Directive, ElementRef, and Renderer from Angular&nbsp; core library<\/li>\n\n\n\n<li>Create a TypeScript class<\/li>\n\n\n\n<li>Decorate the class with @directive<\/li>\n\n\n\n<li>Set the value of the selector property in @directive decorator function. The directive would be used, using the selector value on the elements.<\/li>\n\n\n\n<li>In the constructor of the class, inject ElementRef and Renderer object.<\/li>\n<\/ol>\n\n\n\n<p>We are injecting ElementRef in the directive\u2019s constructor to access the DOM element. We are also injecting Renderer in the directive\u2019s constructor to work with DOM\u2019s element style. &nbsp;We are calling the renderer\u2019s setElementStyle function. In the function, we pass the current DOM element by using the object of ElementRef and setting the color style property of the current element. We can use this attribute directive by its selector in AppComponent as shown in the next listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Component(\n    {\n        selector: 'app-container',\n        template: `&lt;p chcolor>{{message}}&lt;\/p>`\n    })\nexport class AppComponent {<\/pre>\n\n\n\n<p>We used an attribute directive on a<\/p>\n\n\n\n<p>element. It will change the color of the paragraph text to red. &nbsp;Also, we need to declare the attribute directive at the app.module.ts as shown in the next listing:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>We need to import the directive<\/li>\n\n\n\n<li>We need to declare the directive<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"app-module-ts\">app.module.ts<\/h2>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import\u00a0{\u00a0ChangeColorDirective\u00a0}\u00a0from\u00a0'.\/task\/taskcolor.directive';\n \nimport\u00a0{\u00a0app_routing\u00a0}\u00a0from\u00a0'.\/app.routing';\nimport\u00a0{\u00a0DataService\u00a0}\u00a0from\u00a0'.\/shared\/data.service';\n \n@NgModule({\n\u00a0\u00a0\u00a0\u00a0imports:\u00a0[BrowserModule,\u00a0FormsModule,\u00a0HttpModule,\u00a0app_routing],\n\u00a0\u00a0\u00a0\u00a0declarations:\u00a0[AppComponent,\u00a0TasksComponent,\u00a0HomeComponent,\u00a0AddtaskComponent,\u00a0ChangeColorDirective],\n\u00a0\u00a0\u00a0\u00a0providers:\u00a0[DataService],\n\u00a0\u00a0\u00a0\u00a0bootstrap:\u00a0[AppComponent]\n})\nexport\u00a0class\u00a0AppModule\u00a0{\u00a0}<\/pre>\n\n\n\n<p>Here we are importing the ChageColorDirective and also declaring it in the app.module. After doing this, we should be able to use the attribute directive in all the components.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"user-input-in-attribute-directive\">User Input in attribute directive <\/h2>\n\n\n\n<p>We may have a requirement to apply an attribute directive on the basis of some user inputs to change the color of the element when the user mouses over or mouse hovers on the element. To do this, we need to:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>capture user input or action, and<\/li>\n\n\n\n<li>apply a color or clear color respectively.<\/li>\n<\/ol>\n\n\n\n<p>On various user actions, we can call different methods to handle the user actions. To enable methods to handle user actions such as mouse enter, we need to decorate methods with the <b>@HostListener<\/b> decorator. &nbsp;We can modify directives to handle user input as shown in the next listing.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import\u00a0{\u00a0Directive,\u00a0ElementRef,\u00a0Renderer,\u00a0HostListener,\u00a0Input\u00a0}\u00a0from\u00a0'@angular\/core';\n \n@Directive({\n\u00a0\u00a0\u00a0\u00a0selector:\u00a0'[chcolor]'\n})\nexport\u00a0class\u00a0ChangeColorDirective\u00a0{\n\u00a0\u00a0\u00a0\u00a0constructor(private\u00a0el:\u00a0ElementRef,\u00a0private\u00a0render:\u00a0Renderer)\u00a0{\u00a0}\n \n\u00a0\u00a0\u00a0\u00a0@HostListener('mouseenter')\u00a0methodToHandleMouseEnterAction()\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.changecolor('red');\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\u00a0\u00a0@HostListener('mouseleave')\u00a0methodToHandleMouseExitAction()\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.changecolor('blue');\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\u00a0\u00a0private\u00a0changecolor(color:\u00a0string)\u00a0{\n \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.render.setElementStyle(this.el.nativeElement,\u00a0'color',\u00a0color);\n\u00a0\u00a0\u00a0\u00a0}\n}<\/pre>\n\n\n\n<p>As you can probably tell, we have added two methods to handle user actions. On mouse enter and mouse leave, we are changing the color to red and blue respectively.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"passing-data-to-the-directive-with-binding\">Passing data to the directive with binding <\/h2>\n\n\n\n<p>So far we have hard coded the value of the color to the directive. In this next section, let us pass data to the directive with binding. To bind the directive with data, we will use the <b>@Input()<\/b> decorator and add a property in the directive class:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@Input('chcolor')\u00a0highlightColor:\u00a0string;<\/pre>\n\n\n\n<p>The attribute directive can be used as follows:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;p\u00a0[chcolor]=\"color\">{{message}}&lt;\/p><\/pre>\n\n\n\n<p>Let us rewrite the attribute directive to get data from the binding. The element to which the attribute directive will be bound will pass color data.&nbsp; If the element is not binding color data to the attribute binding, the default color red would be used.<\/p>\n\n\n\n<p>This directive can be recreated as shown in the next listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import\u00a0{\u00a0Directive,\u00a0ElementRef,\u00a0Renderer,\u00a0HostListener,\u00a0Input\u00a0}\u00a0from\u00a0'@angular\/core';\n \n@Directive({\n\u00a0\u00a0\u00a0\u00a0selector:\u00a0'[chcolor]'\n})\nexport\u00a0class\u00a0ChangeColorDirective\u00a0{\n\u00a0\u00a0\u00a0\u00a0private\u00a0_defaulColor\u00a0=\u00a0'red';\n\u00a0\u00a0\u00a0\u00a0@Input('chcolor')\u00a0highlightColor:\u00a0string;\n \n\u00a0\u00a0\u00a0\u00a0constructor(private\u00a0el:\u00a0ElementRef,\u00a0private\u00a0render:\u00a0Renderer)\u00a0{\u00a0}\n \n\u00a0\u00a0\u00a0\u00a0@HostListener('mouseenter')\u00a0methodToHandleMouseEnterAction()\u00a0{\n \n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0console.log(this.highlightColor);\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.changecolor(this.highlightColor\u00a0||\u00a0this._defaulColor);\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\u00a0\u00a0@HostListener('mouseleave')\u00a0methodToHandleMouseExitAction()\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0console.log(this.highlightColor);\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.changecolor(null);\n\u00a0\u00a0\u00a0\u00a0}\n \n\u00a0\u00a0\u00a0\u00a0private\u00a0changecolor(color:\u00a0string)\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.render.setElementStyle(this.el.nativeElement,\u00a0'color',\u00a0color);\n\u00a0\u00a0\u00a0\u00a0}\n}<\/pre>\n\n\n\n<p>We can pass data through binding to the attribute directive as shown in the next listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\u00a0\u00a0@Component({\n\u00a0selector:\u00a0'app-container',\n\u00a0template:\u00a0`\n\u00a0&lt;div>\n\u00a0\u00a0\u00a0\u00a0\u00a0&lt;input\u00a0type=\"radio\"\u00a0name=\"colors\"\u00a0(click)=\"color='blue'\">blue\n\u00a0\u00a0\u00a0\u00a0\u00a0&lt;input\u00a0type=\"radio\"\u00a0name=\"colors\"\u00a0(click)=\"color='orange'\">orange\n\u00a0\u00a0\u00a0\u00a0\u00a0&lt;input\u00a0type=\"radio\"\u00a0name=\"colors\"\u00a0(click)=\"color='green'\">green\n\u00a0&lt;\/div>\n\u00a0&lt;p\u00a0[chcolor]=\"color\">{{message}}&lt;\/p>`\n\u00a0})\n\u00a0export\u00a0class\u00a0AppComponent\u00a0{<\/pre>\n\n\n\n<p>We are creating a radio button and binding the value of the color on the click event of the button to the attribute directive. We can select a color from the radio button, and on mouse enter the color would be changed to the selected value.<\/p>\n\n\n\n<p>In a real application, we may fetch data from a REST service and bind to attribute directive.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"conclusion\">Conclusion <\/h2>\n\n\n\n<p>In this post we learned about Attribute Directives in Angular , and created them to change the behavior or appearance of an element, and bound it to the data of the element. I hope you find this post useful. Thanks for reading!<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"\/products\/ignite-ui-angular\/getting-started#installation\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" src=\"https:\/\/download.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-Angular\/Blog-incontent-Ignite-UI-for-Angular-650x200.png\" alt=\" \"\/><\/a><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we will learn how to create Attribute Directives in Angular. So let\u2019s say we want to change the background color of an element; in that case we would apply the attribute directive to the element.<\/p>\n","protected":false},"author":65,"featured_media":1572,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,17],"tags":[],"class_list":["post-600","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular","category-how-to"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/600","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=600"}],"version-history":[{"count":3,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/600\/revisions"}],"predecessor-version":[{"id":2203,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/600\/revisions\/2203"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/1572"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=600"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=600"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=600"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}