Components in Angular 14 and how to create them.

Abdul Kyume Takbir
2 min readOct 7, 2023

What are components in Angular?

Components are the basic building blocks of Angular applications. They are reusable pieces of code that can be used to create different parts of the user interface, such as headers, footers, navigation bars, and product listings.

Components are made up of three parts:

  • Template: The template is the HTML code that defines the structure of the component.
  • Styles: The styles are the CSS code that defines the appearance of the component.
  • Class: The class is the TypeScript code that defines the logic of the component.

Components are decorated with the @Component() decorator. This decorator specifies the metadata for the component, such as its selector, template, and styles.

How to create components in Angular 14

The Angular CLI is a tool that can be used to generate and manage Angular applications. To create a component using the Angular CLI, run the following command:

ng generate component <component-name> --standalone

This will generate a new standalone component with the specified name, including the template, styles, and class files. The decorator should specify the metadata for the component, such as its selector, template, and styles, as well as the imports property. The imports property is an array of Angular modules that the component depends on.

For example, the following component imports the RouterModule module:

import { Component, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css'],
standalone: true,
imports: [RouterModule]
})
export class MyComponent {
// Component logic goes here
}

Once you have created a standalone component, you need to bootstrap it using the bootstrapApplication() function. To do this, create a new file called main.ts and add the following code

import { bootstrapApplication } from '@angular/platform-browser';
import { MyComponent } from './my-component/my-component.component';
bootstrapApplication(MyComponent);

Now you can run the application using the following command:

ng serve

This will start the Angular development server and open the application in a web browser.

Benefits of standalone components

Standalone components offer several benefits, including:

  • They simplify the development process by eliminating the need for custom Angular modules.
  • They provide greater flexibility by allowing you to reuse components across different applications.
  • They improve performance by reducing the amount of code that needs to be compiled.

Conclusion

Standalone components are a powerful new feature in Angular 14. By understanding how to create and use standalone components, you can write more modular, maintainable, and performant Angular applications.

--

--