Steps to create Angular standalone components (no ngModule required) in angular

Akash Chauhan
6 min readNov 9, 2022

--

Components are the basic building blocks of Angular applications. A component is a self-contained code unit that has associated view templates and styles. Components can be used in Angular without a module. This is known as a standalone component.

In this artice , i am going to create an angular standalone component.

The idea behind angular standalone component is to make it easy to reuse and reason about code. When you create a standalone component, you are creating a self-contained unit of functionality that can be used in any Angular application.

There are many benefits to using standalone components in your Angular applications. Standalone components can improve the modularity and testability of your code, and they can make your code more maintainable in the long run.

Angular 14 introduces an alternative method of writing apps, standalone components, directives, and pipes.

When working with Angular, you may find yourself needing to create a standalone component. This is a simple process that can be done in just a few steps.

Learning Objective

  • Steps to create angular standalone component and find the code on github
  • Angular standalone component lazy loading
  • Standalone flag and component imports
  • Using node module in standalone component
  • Standalone component advantages
  • Conclusion

Steps to create angular standalone component

First create a new application having angular cli 14.

Now we have to provide some data to render onto DOM, to do that i am going to create a service file and add some data to an object.

It will look something like this:

import { Injectable } from '@angular/core';export interface Book {
name: string;
id: number;
description: string;
imageUrl: string;
}
@Injectable({
providedIn: 'root'
})
export class BooksService {
books: Book[] = [
{
name: 'Book 1',
id: 1,
description: 'Book description 1',
imageUrl: 'https://cdn.pixabay.com/photo/2015/06/02/12/59/book-794978_960_720.jpg'
},
{
name: 'Book 2',
id: 2,
description: 'Book description 2',
imageUrl: 'https://cdn.pixabay.com/photo/2015/06/02/12/59/book-794978_960_720.jpg'
},
{
name: 'Book 3',
id: 3,
description: 'Book description 3',
imageUrl: 'https://cdn.pixabay.com/photo/2015/06/02/12/59/book-794978_960_720.jpg'
},
{
name: 'Book 4',
id: 4,
description: 'Book description 4',
imageUrl: 'https://cdn.pixabay.com/photo/2015/06/02/12/59/book-794978_960_720.jpg'
}
];
constructor() { }
}

A component is a self-contained unit of an Angular application. A component can be used in any other Angular application as a standalone element. The process of creating a standalone component is simple and only requires a few steps.

First, create a new file for the component. The file should have the same name as the component, and it should be placed in the src/app folder. In the new file, add the following code:

Now lets create our first angular standalone component it will look like this:

Lets have some html and css to render the data from bookService. You can see the standalone attribute added into the component decorator that’s how you make it sure that the component is now standalone.

Here is the default look for the component you’ve created:

I am going to add something to show in the component:

import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BooksService } from './books.service';
import { RouterModule } from '@angular/router';
import {MatButtonModule} from '@angular/material/button';
@Component({
selector: 'app-book-list',
standalone: true,
imports: [CommonModule, RouterModule, MatButtonModule],
template: `
<section>
<div class="grid-container">
<ng-container *ngFor="let book of bookService?.books; let i = index">
<div class="grid-item" [routerLink]="'/details/' + i">
<h3>{{ book?.name }}</h3>
<img width="200" height="200" [src]="book?.imageUrl" [alt]="book?.name"/>
<div class="">
<button mat-raised-button>Add to cart</button>
</div>
</div>
</ng-container>
</div>
</section>
`,
styles: [
`
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
background-color: #2196f3;
padding: 10px;
}
.grid-item {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid rgba(0, 0, 0, 0.8);
padding: 20px;
cursor: pointer;
font-size: 30px;
text-align: center;
}
.cart-button {
margin-bottom: 20px
}
.cart-button button {
margin-top: 20px;
}
`,
],
})
export class BookListComponent implements OnInit {
constructor(readonly bookService: BooksService) { }
ngOnInit(): void { }
}

Angular standalone component lazy loading

Lazy loading standalone components ccan also help reduce the size of your application. When only the necessary components are loaded on demand, you can avoid loading unused code and data. This can help keep your application size down and improve performance.

If you’re looking to improve the performance of your Angular application, consider using standalone component lazy loading. It’s an easy way to improve performance and keep your application size down.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'book-list' },
{ path: 'book-list', loadComponent: () => import('./book-list.component').then(mod => mod.BookListComponent)},
{ path: 'details/:index', loadComponent: () => import('./book-view.component').then(mod => mod.BookViewComponent) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Standalone flag and component imports

When creating a new component using the Angular CLI, the CLI will automatically generate a flag for the component. This flag tells Angular that this is a standalone component and should be treated as such. The generated code for the flag looks like this:

Component, directives, pipes, and components can now be marked as standalone: true. The Angular compiler will now declare that Angular modules should not be declared in the event the class is not marked as standalone.

Standalone components compel their dependencies directly, rather than getting them through NgModules.

@Component({
standalone: true,
selector: 'book-list',
imports: [BookListComponent],
template: `
...
`,
})
export class BookListComponent {
// component logic
}

Components can additionally be referenced with imports. In this manner, there is no need to create an NgModule to store template dependencies when composing a standalone is concerned.

Using node module in standalone component

In Angular, a standalone component is a self-contained unit that represents a piece of the user interface. Each component is a TypeScript class with an associated template.

A component can import one or more modules, which helps to keep the code organized and modular.

When you create a standalone component, you can import one or more modules into it. This helps to keep your code modular and easy to understand.

Standalone component advantages

One of the great things about Angular is that you can create standalone components. Standalone components have many advantages, including:

  • The learning experience benefits from removing the element of complexity at lower entries.
  • This is intended to quicken build times.
  • Angular standalone component still permits to be lazy load.
  • You can even use NgModule-based components and standalone ones with a zoneless technique. Collaborating to decide when to introduce this innovation is not difficult, but there is no rationale to realize this suggestion at present.
  • There are no implied dependencies.
  • Less boilerplate to write means there are fewer files.

Find this code on Github

Conlusion

In conclusion, Angular standalone components are easy to create. You don’t need an ngModule and you can use them anywhere in your Angular application.

The advantages of using standalone components in Angular are many. They allow for a more modular approach to development, greater reusability, and increased efficiency.

In addition, they can be used to create more responsive and user-friendly applications.

Just remember to include the Component directive and the necessary imports. With a few simple steps, you can create your own Angular standalone components.

Originally published at https://www.akashminds.com.

--

--

Akash Chauhan
Akash Chauhan

Written by Akash Chauhan

Akash Expertises in front-end technologies including javascript, Angular,Rxjs, React.js, HTML, CSS and Jquery.

No responses yet