Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Generating a Component Using the CLI

ng generate component is a simple one-line command which creates different files and a folder, and it references the newly created component to the module file.

Dec 20, 2019 • 9 Minute Read

Introduction

"Component" is a booming word nowadays and is one of the widest used terms in the world of front-end web development. Every Javascript-based framework or library must contain a file called "component," whether Angular, React, or Vue.js, because it is one of the building blocks for any application that follows component-based architecture. Let's have a quick introduction to the component in Angular and learn about the CLI.

What is a Component in Angular?

Angular is a popular Javascript framework used to develop MVC architecture-based web, desktop, and mobile applications. A component is an important part of Angular because even a simple app should have at least one component to run the application, called an app component. It is created automatically when we create a new Angular app using the CLI command. The component in Angular is the class that directly interacts with the template and renders the different HTML elements on the browser.

What is Angular CLI

?

Angular CLI stands for Command Line Interface, which is used to start an Angular app quickly, with minimal setup and without custom configuration. Angular CLI has a set of commands that create the file from scratch, update the file, create app configuration, and so on. The most important feature of CLI is that it starts the local web server so as soon as the application’s files are compiled, we can view the output on default Angular URL ‘localhost:4000’. To get started with the Angular CLI, we need to install it using the below-given command.

      npm install -g @angular/cli
    

You can use this command into the command prompt or terminal.After the execution of the command, check the version with another command, which is given below.

      Ng –v
    

OR

      Ng version
    

Here –v stands for the version of the Angular CLI installed in the machine, so after running the above command, we can see this information.

      @angular/cli: 9.x.x

node: 10.x.x

os: your o/s name
    

Why Use Angular CLI

Angular CLI is an effectively handy command-line interface that comes with a huge number of commands that allow us to set up our Angular application quickly and get started with minimal application structure.

It includes a list of commands that allow us to generate different files based on different users, listed below.

  • Component
  • Module
  • Directive
  • Enum
  • Pipe
  • Service

Here is a simple example to generate new service in Angular .

      Ng generate service mydataservice
    

So after executing the above command, you will be able to see that the newly added file of the service is automatically referenced into the module.

How to Create a New Component Using Angular CLI

To create the component, we can use the below ng command followed by a suitable name.

      Ng generate component component_name
    

OR

      Ng g c component_name
    

These are the two main ways to generate a new component in Angular: using ng g c <component_name>, and using ng generate component <component_name>. Using either of these two commands, the new component can be generated pretty easily and followed by the suitable component name of your choice.

Isn’t it really simple?

Yes, it’s just a one-line command which creates different files and a folder, and most importantly it also references the newly created component to the module file so that we don’t need to configure it on our own.

Let’s create a new component called ‘test’ using the below command.

      Ng generate component test
    

After running the above command, we can see the file structure looks like this.

As we can see, we have four different files for different usage.

  • test.component.ts (Class with @Component decorator)
  • test.component.spec.ts (For test case specification)
  • test.component.html (For the template)
  • test.component.css (For stylesheets)

If you notice the last line, there is one file which is updated called app.module.ts, just because we have to reference the newly created component to our root module file so that the Angular CLI automatically does the job while generating the component.

Let’s see the default content of the newly created files, which are described below.

test.component.ts

      import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
    

test.component.spec.ts

      import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TestComponent } from './test.component';

describe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});
    

test.component.html

      <p>test works!</p>
    

test.component.css

In this file, we do not have any classes generated for our test component so the file is empty.

Apart from this file, there is one crucial change, which is to update the reference of the newly created component in the root module. The file will look like this:

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 { HttpClientModule } from '@angular/common/http';
// Newly added component
import { TestComponent } from './test/test.component';

@NgModule({

  declarations: [
    AppComponent,
    // Reference
    TestComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]

})

export class AppModule { }
    

As you can see, the test component is auto-imported from the location where it is created and referenced in the same component in the imports: [] section automatically.

This is how to generate a component from scratch using the CLI command along with a suitable name. In the same way, we can also create other types of files using the CLI, such as service, directive, pipes, enum, and so on.

Using CLI in Other Ways

The Angular CLI is not only available to create the component or files, but it is also useful for many other purposes, such as deployment, adding new third party libraries into the project, creating a new Angular app, updating existing dependencies, testing the use cases, multilingual support, and so on.

Below is the list of commands we can use with the installation of the Angular CLI:

  • Ng update
  • Ng add
  • Ng help
  • Ng deploy
  • Ng build
  • Ng serve
  • Ng version
  • Ng test
  • Ng run
  • Ng doc
  • Ng e2e

There are the few other commands which are supported by the Angular CLI based on the different usage. For example Ng deploy which is specifically used to create build and deploy application into the server, hence we have options of plenty of commands to avail third-party libraries and so on.

For example, if we want to add any third-party library, we can use the below command.

      Npm Install angular-ui-bootstrap
    

The above command will bring us the complete bootstrap user interface package and will now be available for use in our Angular application.

This is how we can use different Angular CLI commands to perform specific actions based on our business requirements.

Conclusion

In this guide, we have learned what the Angular CLI is and why we need to use it. In fact, it can save a lot of time for a developer due to its flexibility and ability to quickly generate a file by just using simple commands.

There are tons of other options available for Angular CLI, which can help a developer to pace up product development time and cost.

Hope you like this guide. If you have any queries regarding this topic, feel free to contact me at CodeAlphabet.