Syntax error: Custom directive

Hey folks,

I was trying to include a directive that I found online - only for testing, but I keep getting an syntax error :frowning:

import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {
    private el: HTMLElement;

    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

The output at the console is the following:

SyntaxError: /home/myTutorial/app/directives/highlight.js: Unexpected token (5:12) while parsing file: /home/myTutorial/app/directives/highlight.js

Does someone know, how to fix this error?

Thanks,
Oliver

You use typescript syntax in js.

You are feeding TypeScript to a JavaScript project. I strongly recommend making a TypeScript project, but if you insist on using JavaScript, you must figure out how to manually translate your TypeScript sample code.

I’m pretty new to Angular2 - how can I convert it?

First: try rename highlight.js to highlight.ts
If it doesn’t help, than you need create TS project. You could read about it in documentation.

Hello @odorakel

If you are very new and starting to learn, I would strongly recommend to work with typescript directly instead of ES5 or ES6. Most of the samples you see in web and in official angular 2 website, mostly it will be typescript.

Regards
Vijay

1 Like

Ok, thanks for the advice - I do created now a Typescript Ionic2 project.

But I also have a “normal” one with javascript and I was trying to get this working, but it won’t work for some reason. I wanted to test this tutorial directive called “Elastic header”.

http://www.joshmorony.com/how-to-create-a-directive-in-ionic-2-parallax-header/

Just to add a bit more to this, if you wanted, you could have done the following

import { Directive, ElementRef } from '@angular/core';
@Directive({ selector: '[myHighlight]' })

export class HighlightDirective {
   static get parameters(){
    return [[ElementRef]];
  }

    constructor(el) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

This will make sure everything is done correctly and won’t give you any syntax errors.