Search code examples
angularjsangularangular2-directives

Angular 2 Directive


I have a question according to Angular 2 directives. I want to recreate my Angular 1 Application with Angular 2 but I got stuck at a directive. The one in Angular 1 looks like this:

app.directive('starRating', function () {
  return {
    restrict: 'A',
    template:   '<ul class="rating">' +
                    '<li ng-repeat="star in stars">' +
                        '<span class="glyphicon" ng-class="star.class" aria-hidden="true">' +
                    '</li>' +
                '</ul>',
    scope: {
        ratingValue: '=',
        max: '='
    },
    link: function (scope, elem, attrs) {
        scope.stars = [];
        for (var i = 0; i < scope.max; i++) {
            if(i < scope.ratingValue){
                scope.stars.push({
                    class: "glyphicon-star"
                });
            } else {
                scope.stars.push({
                    class: "glyphicon-star gray"
                });
            }
        }
    }
  }
});

and I call it in my html file like this:

<div star-rating rating-value="movie.rating" max="5" ></div>

It's just a somple movielist with a name and the rating. Through the directive, I want to create just 5 stars and depending on the rating, the number of stars should be filled.

Is it possible to do such in Angular 2 aswell? If so, how would it be done? I cant find any proper code example or tutorial.

Thanks Peter


Solution

  • ok I found myself a fitting solution:

    in the component i just added a function

    getClass(index, rating) {
        if (index < rating) {
            return 'glyphicon-star';
        } else {
           return 'glyphicon-star-empty gray';
        }
    }
    

    in my HTML i call it like this:

    <div class="col-lg-3">
       <ul class="rating">
           <li *ngFor="let n of [0,1,2,3,4]; let i = index">
               <span class="glyphicon" [ngClass]="getClass(i, rating)"></span>
           </li>
       </ul>
    </div>