Rando Hinn Rando Hinn - 5 months ago 51
AngularJS Question

Angular2 custom directive issues

Mkay, I was following a tutorial online, this one, to be percise, the result of which was a directive as such:

import {Component, View} from 'angular2/core';

@Component({
selector: 'rating',
})

@View({
template: `
<span tabindex="0">
<template NgFor="#val of range" #index="index">
<span class="sr-only">(*)</span>
<i class="glyphicon glyphicon-star"></i>
</template>
</span>
`,
directives: [NgFor]
})

export class Rating {
private range:Array<number> = [1,2,3,4,5];
}


Seeing various errors here:


  1. NgFor is not defined

  2. If I import NgFor, then core_1.View is not a function


Answer
  • @View() was removed in beta.10. Move the parameters to @Component() instead
  • NgFor is part of CORE_DIRECTIVES no need to add them to directives: [] anymore (was required in older versions)
  • the ngFor syntax in your template was kind of a mix of shorthand and full syntax

1) directly applied to a tag (shorthand)

<li template="ngFor let item of items; let i = index">...</li>

2) using a wrapping <template> tag (full)

<template ngFor let-item [ngForOf]="items" let-i="index"><li>...</li></template>

See also NgFor

corrected code

import {Component, View} from 'angular2/core';

@Component({
   selector: 'rating',
  template: `
      <span tabindex="0">
          <template ngFor let-val [ngForOf]="range" let-index="index">
              <span class="sr-only">(*)</span>
             <i class="glyphicon glyphicon-star"></i>
          </template>
     </span>
 `,
  directives: []
})

export class Rating {
    private range:Array<number> = [1,2,3,4,5];
}