Yahya Hussein
Yahya Hussein

Reputation: 9101

Angular 4 Component is rendered as empty

I am new to Angular, I am trying to define a component and use it in my main page.

The thing is that when using the component in index.html all I can see is my <custom-component></custom-component> empty, nothing inside it.

So what I did is:

What did I miss?

Update: Code of my component:

custom.component.html

<p>
 component works!
</p>

custom.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> 
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-custom></app-custom>
</body>
</html>

app.module.ts:

import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http'; 
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Upvotes: 5

Views: 9537

Answers (3)

Roger Xi
Roger Xi

Reputation: 99

In NgModule.bootstrap, add your own component.

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

Upvotes: 3

andrea06590
andrea06590

Reputation: 1299

Try to add exports after declarations => [AppComponent, CustomComponent] ? in app.module. Or create a new cli project with the last version

Upvotes: 6

Try this in index.html add the Appcomponent selector tag and inside Appcomponent template refer your custom component selector and don't forgot to import and declare the custom component in app module and bootstrap the Appcomponent so it renders the app component on load which internally refers your custom component. There are many tutorials outside just start with a single component if you are using AngularCli everything is made easy for you.

Upvotes: 0

Related Questions