Search code examples
angularangular2-directivesangular2-components

Angular 2 directives error


I'm using the final Angular 2 release version. I have set up the startup file as mentioned in official site angular 2 quickstart. In my app.component.ts file I've made 2 components. The code is shown below:-

    import { Component, OnInit} from '@angular/core';

@Component({
    selector: 'demo',
    template:`
        <h2>Hi, demo !!</h2>
    `
})

export class DemoComponent implements OnInit{
    constructor(){}

    ngOnInit(){

    }
}

@Component({
  selector: 'my-app',
  template: `<h1>My First Angular 2 App</h1> 
    <demo></demo>
    `

})
export class AppComponent implements OnInit{ 
    constructor(){}
    ngOnInit(){

    }
}

In the component of my-app I've used directives selector which is an array. But the editor(VS Code) is showing error. The console of chrome is throwing an error, telling that Template parse errors: 'demo' is not a known element: Chrome console

please help me fix this. Thanks

Here's my app.module.ts file

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, DemoComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

Solution

  • You have to define your component in the declarations property of your module.

    app.module.ts

    import { AppComponent, DemoComponent  }   from './app.component';
    
    @NgModule({
      imports:      [ BrowserModule ],
      declarations: [ AppComponent, DemoComponent ], <== here
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    And remove it from directives property of AppComponent. It is deprecated.

    app.component.ts

     directives: [DemoComponent] ,