Dynamic html rendering in angular using directive
Posted By : Avilash Choudhary | 15-Dec-2017
Hi Guys,
As you already know, Angular2 or Angular is now getting popular. It really good for large applications where you can design different components and use them multiple times wherever required. Angular don't recommend manipulating dom directly because its really costly for performance wise. Angular does all the dom manipulation task. But there are cases where we need to manipulate dom, for these cases we can use directive. Directives are very helpful, they are usable. you don't need to write code for multiple places. Just put the directive tag in the html Element wherever required. It will do the task.
Lets you have html tag and put directive
app.component.html <section class="list-panel list-tab" sidebar></section> // your directive file will look like this import { Directive,Input, ElementRef, Renderer2 } from '@angular/core'; @Directive({ selector: `[sideBar]` }) export class SideBarDirective { constructor(public el: ElementRef,public renderer:Renderer2) {} ngAfterViewInit(){ this.el.nativeElement // this will give the reference of element where you put the directive // angular dont recommend using native element directly, use it with the help of renderer this.renderer.setStyle( this.el.nativeElement,'color','green'); } }
This is a way, you can manipulate any style property of html element, also append,prepend the html inside element and also bind the event listeners with the html element and perform action such as click event etc. Here you can use pure javascript to create you html elements and render them into your template file.
Host binding can also be used to listen to global events. To listen to global events, a target must be added to the event name. The target can be document,window or body.
Here we have used the renderer2 because renderer is deprecated in angular2. RendererV2 does not have listenGlobal function now for global events like(document,body,window). It achieves both functionalities with the only listen function.
You can also find div EventListener which has two event: mouseenter and mouseleave. when you move the mouse in div, you can change the color and when mouse leave change color.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.