Angular 2 directive to append HTML in directive selector

Angular 2 directive to append HTML in directive selector.

I was trying creating a star rating directive for angular 5 project. It was really hard search for me to insert HTML in to directive selector.

I know an component can easily allows access to append HTML inside the element. But i needed to do this for directives as i was already using the component for product box layout.

  1. USING COMPONENT

In template:

<div [innerHTML]="ratingHtml" class="rating"></div>

In Class:

import { Component, OnInit,Input} from ‘@angular/core’;

@Component({
selector: ‘app-block-product’,
templateUrl: ‘./block-product.component.html’,
styleUrls: [‘./block-product.component.css’]
})
export class BlockProductComponent implements OnInit {

ratingHtml =”;

constructor(
) { }

ngOnInit() {
this.generateRatingHtml(this.product.avg_r);
}

generateRatingHtml(rating){
var html=”; var active=”;
for(var $i=0;$i<5;$i++){
if($i < rating){ active = ‘checked’; }else{ active=”;}
html+='<span class=”fa fa-star ‘+active+'”></span>’;
}
this.ratingHtml = html;
}

}

 

2. USING DIRECTIVE

In template.

<span appStars=”{{item.avg_r}}”></span>

In Class:

import { Directive,Renderer2,Input,OnInit,ElementRef} from ‘@angular/core’;

@Directive({
selector: ‘[appStars]’
})
export class StarsDirective {

@Input(‘appStars’) rating: any;
ratingHtml:any;

constructor(
private el: ElementRef,
private renderer :Renderer2
) { }

ngOnInit() {
this.rating = parseInt(this.rating);
this.generateRatingHtml(this.rating);
this.el.nativeElement.innerHtml = this.ratingHtml;
}

generateRatingHtml(rating){
this.renderer.addClass(this.el.nativeElement,’rating’);
var html=”; var active=”;
for(var $i=0;$i<5;$i++){
if($i < rating){ active = ‘checked’; }else{ active=”;}
html+='<span class=”fa fa-star ‘+active+'”></span>’;
}
this.ratingHtml = html;
this.renderer.setProperty(this.el.nativeElement, ‘innerHTML’, this.ratingHtml);
}

}

Now i know this directive is reusable and i am able to insert HTML dynamically through renderer2 in angular 5 project.