Telerik blogs

In this article, we will look at how to use the Angular CLI to create components.

Angular is a framework that lets us create interactive web frontends for users. It comes with the Angular CLI that lets us create project files easily.

Angular CLI has many options that let us create various files like components, directives, modules, guards and more. Also, it creates the associated test files along with the project files automatically, also registering the files in the module if required. The TypeScript compiler and other build tools are also added automatically.

Therefore, most projects are created with the Angular CLI to make managing the project easy.

In this article, we will look at how to use the Angular CLI to create components.

Basic Usage of Ng Generate

To use ng generate to create component files along with the associated test files, we run:

ng generate component

We can shorten that to:

ng g component

Other project files that we can create with ng generate include:

  • app-shell
  • application
  • class
  • component
  • directive
  • enum
  • guard
  • interceptor
  • interface
  • library
  • module
  • pipe
  • resolver
  • service
  • service-worker
  • web-worker

We can also run it with a few flags.

The --defaults flag makes ng g run with all the default values set.

The --dry-run flag lets us run ng g without actually creating the files. Rather, it just shows us what changes will be done when we run it without the flag.

--force lets us force overwriting of existing files.

--help shows us the help message for the command we have before the flag.

--interactive enables interactive input prompts.

They are all boolean flags.

Ng Generate Components & Options

To create components, we run ng g with the component name. For instance, we run:

ng g component Foo

to create the Foo component, register it in the default module and add the associated test files.

ng g component comes with its own options.

The --change-detection flag lets us set the change detection strategy for the component.

--display-block lets us add :host { display: block; } to the file when we generate it.

--export lets us export the component. It’s a boolean flag.

--flat creates new files at the top level of the current project. It’s a boolean flag.

--inline-style makes Angular CLI put the styles in the component file as a string instead of in a separate file. It’s a boolean flag.

--inline-template makes Angular CLI put the template in the component file as a string instead of in a separate file. It’s also a boolean flag.

--module lets us set the module to register the component in.

--prefix lets us set the prefix for the component selector.

--project lets us set the project the component should be in. It takes a string value.

--selector lets us set the selector name. It takes a string value.

--skip-import makes Angular CLI skip importing the component into a module. It’s a boolean flag.

--skip-selector lets us skip setting the selector name of the component being generated. It’s a boolean flag.

--skip-tests lets us skip creating test files. It’s a boolean flag.

--standalone lets us create a standalone component. It’s a boolean flag.

--style lets us set the CSS preprocessor to use for the file. It can be one of css , scss, sass, less or none.

--type lets us add the TypeScript type definitions we want into a type definition file in the project. It takes a string value.

And --view-encapsulation lets us set the view encapsulation strategy. It can be one of Emulated or None or ShadowDom. View encapsulation lets us isolate a component so that it doesn’t affect the rest of the application.

Using ng g to Generate Component Files

We can use ng g component with the options listed above to create and register our own component.

For instance, we run:

ng g component Foo --inline-style --inline-template --selector FooBar --style scss

to create the Foo component with selector FooBar. And it has inline styles and templates, which are inside the component file.

The preprocessor for the component is scss. As a result, we should see the foo folder in the app folder with the foo.component.ts and foo.component.spec.ts files.

In foo.component.ts, we see:

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

@Component({
  selector: "FooBar",
  template: ` <p>foo works!</p> `,
  styles: [],
})
export class FooComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
}

We see the selector is FooBar which is the same as what we specified with the --selector option.

template is set to a template, which is inline.

In foo.component.ts, we see:

import { ComponentFixture, TestBed } from "@angular/core/testing";

import { FooComponent } from "./foo.component";

describe("FooComponent", () => {
  let component: FooComponent;
  let fixture: ComponentFixture<FooComponent>;

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

    fixture = TestBed.createComponent(FooComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

which is generated by ng g.

It has a test that sets up the component for testing in the beforeEach callback.

We get the component being tested from fixture.componentInstance. Then we call it with the component spec description and a callback that checks that the component is truthy with toBeTruthy.

In app.module.ts, we see:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { FooComponent } from "./foo/foo.component";

@NgModule({
  declarations: [AppComponent, FooComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

We can see that FooComponent is imported and it is registered in the declarations array property. As a result, it is ready to be included in other components in AppModule.

In app.component.html, we replace what is there with:

<FooBar></FooBar>

to show the content of the component we just generated.

Therefore, we see foo works! is displayed on the screen when we run ng serve and go to http://localhost:4200/.

Since we specify the --inline-styles flag when we run ng g component, we can add styles to the styles array property of the component.

For instance, we write:

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

@Component({
  selector: "FooBar",
  template: ` <p>foo works!</p> `,
  styles: [
    `
      p {
        color: red;
      }
    `,
  ],
})
export class FooComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
}

to add a string with the styles array property.

Now the p element is displayed with red text since we set the color style to red.

After creating the component with ng g component, we can still change it later.

For instance, we can create styles and template files manually in the foo folder and then set the templateUrls and stylesUrls properties in the object we call @Component with to specify paths for the external template and style files.

And we can get rid of the template and styles properties if we replace the template and styles with external files.

Conclusion

Angular CLI has many options which let us create various files like components, directives, modules, guards and more. And it automatically creates the associated test files and project files, registers them, and adds the build tools.

We can set many options in the command that we run to create the component. And after that, we can still change the component manually to the way we like.


About the Author

John Au-Yeung

John Au-Yeung is a frontend developer with 6+ years of experience. He is an avid blogger (visit his site at https://thewebdev.info/) and the author of Vue.js 3 By Example.

Related Posts

Comments

Comments are disabled in preview mode.