How to create a new Component in Angular2
Como crear un nuevo Component en Angular2

Hello everyone,
In this post you are going to find how you can create a new Component using Angular CLI, and also add it in an html file.

If you don't know how to create an Angular 2 Project, please see this post to complete it first http://angular2university.blogspot.pe/2017/06/steps-to-build-your-first-angular-2.html


Angular CLI provide us a set of command to create some things of Angular 2, in this case we are going to use the first one.
ScaffoldUsage
Componentng g component my-new-component
Directiveng g directive my-new-directive
Pipeng g pipe my-new-pipe
Serviceng g service my-new-service
Classng g class my-new-class
Guardng g guard my-new-guard
Interfaceng g interface my-new-interface
Enumng g enum my-new-enum
Moduleng g module my-module
Execute this Command to create a 'customers' component.
       
 ng g component customers

       


When the command is finished you should see that a new folder was created as you can see below.


Angular CLI has added an extra declaration into you app.module.ts to import the last component that you added.

app.module.ts
       
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 {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from '@angular/material';
import { CustomersComponent } from './customers/customers.component';

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

        


How can I add this new component in another component?

Just you need use its selector-name Wich you can find it on the customers.component.ts file see the follow picture.
In this case it's called [app-customers]



Now we can write it in anywhere of our application.
For example if we need add this customers component into the app component, you could write the following.


Finally, please Run the application and see the results, You should see as the following picture.


Well Done! Your application has two components so far.

We created a video in Spanish as well😊.

Comments

Popular posts from this blog

Error al Iniciar Oracle SQL Developer 11g - Unable to find Java Virtual Machine

Como Mantener el Scroll despues de un PostBack ASP.net ( As Maintain Scroll after a PostBack ASP.net )

How to run ng serve in a different port
Como ejecutar ng serve en un puerto diferente