Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 { }
like image 653
Yashwardhan Pauranik Avatar asked Nov 28 '25 00:11

Yashwardhan Pauranik


2 Answers

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] ,

like image 110
yurzui Avatar answered Nov 29 '25 15:11

yurzui


directives is deprecated. Create an NgModule and add it to the declarations instead.

https://angular.io/docs/ts/latest/guide/ngmodule.html

like image 34
Rob Avatar answered Nov 29 '25 17:11

Rob