Search code examples
angularangular2-directivesangular2-components

Uncaught Error: Could not compile HighlightDirective because it is not a component


Error Log:

runtime_compiler.js:353Uncaught Error: Could not compile 'HighlightDirective' because it is not a component.assertComponent
...

Directive:

import {Directive, ElementRef, Renderer} from '@angular/core';


@Directive({
  selector: '[dirHighlight]'
})
export class HighlightDirective {

  constructor(private elementRef: ElementRef, private renderer :Renderer) {

  //this.elementRef.nativeElement.style.backgroundColor = 'green';
    this.renderer.setElementStyle(this.elementRef.nativeElement,'background-color', 'green');
  }

}

Html file:

<h2> Custom Attribute Directive</h2>
<div dirHighlight> Some thing</div>

app.component.ts

import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

@Component({
  selector: 'dir-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  entryComponents:[HighlightDirective],

})
export class AppComponent {

}

Solution

  • you need to add Directives in the Main Module you have, not as entryComponents

    import { HighlightDirective } from './highlight.directive';
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [
        AppComponent,
        HighlightDirective
      ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }
    

    Look at the documentation here

    Hope this helps!!