Angular architecture with standalone components (it's easy)
Today we're going to learn about how to do component-first architecture with Angular standalone components.
Learning how to structure your Angular apps is a huge topic.
And with the recent changes in Angular that allow for standalone components we can now structure our apps very differently.
So let's take a look at how this could change the way we structure our Angular apps.
Before we had the option of standalone components we had to declare every component as being part of a module before we could use it.
Obviously the root module was called AppModule
by default and usually found in app.module.ts
.
In summary, we had to do something like this.
import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
template: `{{name}}`,
styles: []
})
export class MyComponent {
name = 'Angular';
}
@NgModule({
imports: [CommonModule],
declarations: [MyComponent],
exports: [MyComponent]
})
export class AppModule {}
But this all changed with standalone components.
Now we can create a simple standalone component and then it can act alone without needing to be part of a module.
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
standalone: true,
template: `{{name}}`,
imports: [CommonModule],
styles: []
})
export class MyComponent {
name = 'Angular';
}
But what benefit does this really give us as developers?
Let's look at some of the differences between the module approach and the standalone component approach and how this affects the way we build and structure Angular apps.
As you can see by the example we make it much simpler
With standalone components we can take out that whole extra step of having to declare modules and hook them together by importing and exporting your components.
This also affected the way we worked with the Angular router.
With Angular modules we had our root level routing module which would set up the forward for our sub-module and lazy load our child modules and their components.
With the standalone components we can only just declare them in the root router.
Another improvement is that the structure of an Angular app has also become much simpler.
You don't need to over-think it. It can be this simple. 😃 😃 😃
+
So what is component first architecture?
When you move towards a standalone component approach for application development you need to fill the void that Angular modules have created.
In older versions of Angular we would see our Angular module first and then move on to the components that were declared as part of that module.
Now your components are standalone and you can focus on splitting them out by feature instead of modules. Along with their own state, etc..
It's simple. Just don't over think it.
And till next time, enjoy modern Angular!
Daniel Kreider - Angular Developer