My current setup includes a template named "starrating.component.html"
<ng-container *ngFor="let star of arrayStarts">
<span class="glyphicon star" aria-hidden="true"
[class.glyphicon-star-empty]="activeStar>=star? false : true"
[class.glyphicon-star]="activeStar<star ? false : true"
(click)="clickStar(star)"
(mouseleave)="mouseleaveStar(star)"
(mouseover)="mouseoverStar(star)" >
</span>
</ng-container>
The corresponding component is "starrating.component.ts"
import { Component } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: 'app/starrating/templates/starrating.component.html',
styleUrls: ['app/starrating/css/style.css']
})
export class StarRatingComponent {
public arrayStarts;
public activeStar;
public selectedStar;
constructor() {
this.arrayStarts = [1, 2, 3, 4, 5];
this.activeStar = 0;
this.selectedStar = -1;
}
mouseoverStar = function (star) {this.activeStar = star;}
mouseleaveStar = function (star) {this.activeStar = this.selectedStar || 0;}
clickStar = function (star) { this.selectedStar = star; }
}
The current functionality is satisfactory, but I am considering using Attribute directives for optimization. I made the following changes:
Updated template "starrating.component.html"
<ng-container *ngFor="let star of arrayStarts">
<span class="glyphicon star" aria-hidden="true"
[starHighlight]="star"
[class.glyphicon-star-empty]="activeStar>=star? false : true"
[class.glyphicon-star]="activeStar<star ? false : true"
>
</span>
</ng-container>
Updated component "starrating.component.ts"
import { Component } from '@angular/core';
@Component({
selector: 'star-rating',
templateUrl: 'app/directives/starrating/templates/starrating.component.html',
styleUrls: ['app/directives/starrating/css/style.css']
})
export class StarRatingComponent {
public arrayStarts;
this.arrayStarts = [1, 2, 3, 4, 5];
}
}
Introducing the directive code in "starrating.directive.ts"
import { Directive, ElementRef, Input, Output, Renderer, HostListener } from '@angular/core';
@Directive({ selector: '[starHighlight]'})
export class StarHighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer) { }
private _selectedStar = -1;
private _activedStar = 0;
@Input('starHighlight') star: any;
@Input('activeStar') activeStar: any;
@HostListener('mouseenter') onMouseEnter() {this._activedStar = this.star;}
@HostListener('click') onMouseCick() { console.log('onMouseCick: set star:', this.star);}
@HostListener('mouseleave') onMouseLeave() { this._activedStar = this._selectedStar || 0; }
}
The events (click, mouseenter, and mouseleave) work perfectly within the directive.
To update the span element based on the "activeStar" variable, the following code should be used:
[class.glyphicon-star-empty]="activeStar>=star? false : true"
However, the value of "activeStar" is now defined within the directive, and passing values from the directive to the template proves challenging. Is there a more effective method to achieve this?