How to manually register a component in AngularJS ?
As we all know, components in angularJS are the basic building blocks of each application. Normally, we can create a component in angular by simply running the following command.
ng g c component_name
This creates a series of files as shown in the below figure. This includes the following files –
- HTML file: For generating HTML DOM (Document Object Model).
- spec.ts file: For running unit test cases of the component.
- component.ts: This is the main file that contains the main logic of the project.
- css file: For adding styles to the web page.
Angular CLI Component Creation
In the last part of component generation by Angular CLI, it just updates the app.module.ts file to include the newly generated component. If you observe closely, this step is just the same step as we have performed in step 3 shown below.
Steps to manually generate a component –
- Create a new folder under ‘app’ folder of the angular project. For this, open your project in any IDE which is comfortable to you. We will be using VS Code IDE here. Now right-click on ‘app’ and click the new folder or click on icons present above to create a folder or manually create a folder from file explorer.
New Folder Creation
- Create a typescript file now. Consider it to be customer.component.ts. Now we will add contents to this file such as template, selector, styles, etc.
customer.component.ts
import { Component } from "@angular/core" ;
@Component({
selector: 'chinmay' ,
template: '<h1> Welcome to manual component creation</h1>' ,
styles: []
}
)
export class CustomerComponent {
}
|
- Now go to app.module.ts file and import your custom-created component into @NgModule declarations section.
app.module.ts
import { BrowserModule } from '@angular/platform-browser' ;
import { NgModule } from '@angular/core' ;
import { AppRoutingModule } from './app-routing.module' ;
import { AppComponent } from './app.component' ;
import { CustomerComponent } from './customer/customer' ;
@NgModule({
declarations: [
AppComponent,
CustomerComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
- For the last and the final step, go to app.component.html file and add the same selector that you have added in the custom component typescript file (custom.ts).
app.component.html
< h1 >Welcome to GeeksForGeeks !! </ h1 >
< chinmay ></ chinmay >
|
- Done !! Now you have successfully created and manually registered a component in Angular. Additionally, you can also create the support files required for supporting the component like CSS styles, HTML, and spec files for unit testing the component.
Project Output on Browser
Last Updated :
26 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...