Syntax error: Custom directive


#1

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


#2

You use typescript syntax in js.


#3

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.


#4

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


#5

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.


#6

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


#7

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/


#8

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.