Angular Component

Angular Component is the main building block to create the Angular Project. You can create components through the Angular CLI command.

How to create the component


ng generate component component-name

OR


ng g c component-name

After run this command 4 files are generated and 1 file is updated.

Suppose, You create users component.


ng g c users

then 4 files are generated


CREATE src/app/users/users.component.html (20 bytes)
CREATE src/app/users/users.component.spec.ts (619 bytes)
CREATE src/app/users/users.component.ts (272 bytes)
CREATE src/app/users/users.component.scss (0 bytes)

and One module file is updated
the updated file is a module file like app.module.ts

When module file is updated then component file is included in two section.
1) imported the component file like


import { UsersComponent } from './users/users.component';

2) Added component into declaration array.


@NgModule({
  declarations: [
    AppComponent,
    UsersComponent
  ], 

Now, You changed the content into users.component.html file.


<h1>Hello users!</h1>

Create the route for the component

Suppose, You want to create route for users component. There are two step to create the route.

Step1) Firstly open the route file and import the users component.
Example:- Now you are including users component into app-routing.module.ts file


import { UsersComponent } from './users/users.component';

Step2) Now, create the route into the Routes Array.


const routes: Routes = [
  {path:'users', component:UsersComponent},
];

Now, run the URL on the browser


http://localhost:4200/users

and output will be