Adding A New Component

on this tutorial, we are going to add a new component to our default project created in angular CLI. so with a new project,,, by now you should have created a new angular project using angular CLI. if you haven not, be sure to go to the first page of this tutorial series.

lets create a new branch called: 2-angular-components

$ git checkout -b 2-angular-components


1. create a new file called: app.car.component.ts and dd the following code:
    import { Component } from '@angular/core';
    @Component({
      selector: 'carApp',
      templateUrl: './app.car.component.html'
    })
    export class CarComponent{
        wheels:number = 4;
    }
    class Car { 
        engine: string;
        constructor(engine: string) {
            this.engine = engine;
        }
    }
    let hondaAccord = new Car('V6'); // hondaAccord is an object
    alert(hondaAccord.engine); // OUTPUT: V6

2. Create a new file: app.car.component.html and dd the following code:
wheels={{wheels}}

3. open app.module.ts
add import { CarComponent } from './app.car.component';
add CarComponent in @NgModule object
app.module.ts should look like this:


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

import { AppComponent } from './app.component';
import { CarComponent } from './app.car.component';

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

run your new code with angular CLI:
ng serve

open your browser to: http://localhost:4200

Save your work with git commit

git add ./

git commit

name it: 2-angular-components

Add Component Using Angular CLI Command

Angular has made it very easy to add components to your projects by simply executing a simple command. to add a component, simply open a terminal in the app/ directory of your project and execute this command.. in this example, i will be creating a component called 'home':

ng generate component home

Thats it! - Angular will generate all the required files to start a new component. once the component has been created, import it in the app.component.ts file and add the directive.

if you still need help, you can check this video out, it contains helpful information about components

https://www.youtube.com/watch?v=YKi2A2PFTnc