Angular has allowed the declaration and use of so-called standalone components for some time now (from Angular 14 on). These are components independent of a module and can therefore be used without the need of declaring them in any module.
How to create a standalone component
Creating standalone components is in principle very easy. You just have to set the standalone
flag in the component decorator to true. But now that the component is no longer embedded in a module, so you also have to import all services and other components used:
@Component({
standalone: true,
selector: 'app-my-component',
imports: [
RouterOutlet,
ReminderComponent
],
templateUrl: './app.my-component.html',
styleUrls: ['./app.my-component.css']
})
export class AppComponent {
}
The imports declaration specifies which other building blocks this component is allowed to use. These can be other NgModules but also other standalone components.
The standalone component already has all the information to act as an independent unit. It is not dependent on a module and does not have to be declared in a module. You can imagine a standalone component as a module and component combined in a single unit.
Bootstrap Angular via a standalone component
Before standalone components were possible, you had to specify the start module in the main.ts, which in turn had to declare the start component. Normally this was AppModule and AppComponent if you created a project with ng.
With the introduction of standalone components, the application can now be bootstraped with a standalone component. There is a new method for this: boostrapApplication
. The first argument to this command is the start component, as the second argument you can specify the service providers used across the application, which you would previously register in the AppModule.
// main.ts
import...
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(HttpClientModule),
provideRouter(APP_ROUTES),
provideAnimations()
]
});
This means that a central AppModule is no longer necessary for an Angular application. As you can also see here, you can import the providers of existing ngModules with the command
importProvidersFrom
This means that the modular and standalone approaches can coexist. So you don't have to decide on an approach overnight and compatibility with existing module code is still guaranteed.
Top comments (2)
Nice article, Stefan! I've no criticism of the comments but you can use syntactic highlighting on dev.to which will make your code examples slightly easier to read. @hoverbaum has written an article which outlines how to do it.
Hi Angus,
thank you for the hint!