Angular 2 Component Not Displaying in index.html

user3355961 picture user3355961 · Apr 26, 2017 · Viewed 21.3k times · Source

Im very new to Angular 2 so bear with me. Im trying to get a new component to appear in the index.html page. The file set is from the basic quick start files from GitHub. I created a new component as such:

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

@Component({
    selector: 'app-user-item',
    template: `<h1>It works!</h1>`,
})
export class UserItemComponent {

}

I have declared the selector tags in HTML as such:

<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('main.js').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>

    <my-app>Loading AppComponent content here ...</my-app>
    <app-user-item>loading another component</app-user-item>
  </body>
</html>

I even tried adding the import to the top of app.module.ts and component name to the declarations array in app.module.ts. But still nothing. I checked my file structure and there is a js version of user-item.component.ts. But I cannot see changes.

Any help would be appreciated.

Cheers

Answer

Tamela  picture Tamela · Mar 20, 2018

I had this exact same problem. In your app.module.ts file make sure to include your component in your bootstrap declaration.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { UserItemComponent } from './UserItem.component';

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