Creating a Component

How to create a component with Angular CLI

Luckily we do not have to write the boilerplate code from the previous section to create a component angular will do that for us. If you have the angular CLI installed we can use it generate a component and all its boilerplate code.

ng generate component <component-name>

BASH Command
ng generate component my
// both commands will do the same thing
$ ng g my

When creating a component with the Angular CLI we do not need to add component to the name, it will do it for use. For example: $ng generate my will generate a file named my.component.ts that has the class MyComponent;

Importing a Component to app.module.ts

After we create a component we must register it in app.module.ts, if you use the CLI to generate the component is should add it for you to the app.module.ts imports list and declarations array, but it best practice to check after each time.

Always confirm something works in programming before moving on. There are times when things do not work as advertised.

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

import { AppComponent } from './app.component';
import { MyComponent } from './my.component';

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

App.module.ts Explanation

Line 6: we are importing the MyComponent from ./my.component.ts. This is a relative file path, what does one dot mean again? Same folder or different folder?

Line 9 my.component.ts - You will see export class MyComponent, this is what is being imported in the app.module.ts

Line 10: Declarations is an array of all components, notice AppComponent and MyComponent are here.

Last updated