Danish Rasheed Danish Rasheed - 2 months ago 6
AngularJS Question

uncaught Error: Could not compile 'HighlightDirective' because it is not a component

Error Log:




  1. runtime_compiler.js:353Uncaught Error: Could not compile
    'HighlightDirective' because it is not a component.assertComponent @
    runtime_compiler.js:353RuntimeCompiler._createCompiledHostTemplate @
    runtime_compiler.js:181(anonymous function) @
    runtime_compiler.js:132(anonymous function) @
    runtime_compiler.js:131(anonymous function) @
    runtime_compiler.js:128RuntimeCompiler._compileComponents @
    runtime_compiler.js:127RuntimeCompiler._compileModuleAndComponents @
    runtime_compiler.js:64RuntimeCompiler.compileModuleAsync @
    runtime_compiler.js:55PlatformRef_._bootstrapModuleWithZone @
    application_ref.js:303PlatformRef_.bootstrapModule @
    application_ref.js:285(anonymous function) @
    main.ts:12__webpack_require__ @ bootstrap a3ac172…:52(anonymous
    function) @ zone.js:1327__webpack_require__ @ bootstrap
    a3ac172…:52webpackJsonpCallback @ bootstrap a3ac172…:23(anonymous
    function) @ main.bundle.js:1




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 {

}

Answer

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!!