Angular v14.x brings standalone components and therefore full Angular CLI support, so we’re going to dive into this new feature to see what the CLI can do for us.
First, we’ll look at creating standalone components, and secondly we’ll modify our angular.json
schema so that all components can be standalone automatically.
A typical Angular CLI command to generate a component looks like so:
# OR use `ng g c pizza`
ng generate component pizza
This would then add the component to an NgModule
for you, which you can specify or not.
So what about standalone components? Thankfully all it takes is a new --standalone
flag:
# OR use `ng g c --standalone pizza`
ng generate component --standalone pizza
This won’t be added to an NgModule
, and will contain the standalone: true
flag inside the @Component
decorator, as well as any other default imports.
But let’s say you want to create all components as standalone, how could this be done?
…It would get a little tiring adding --standalone
to every single Angular CLI command.
Enter the angular.json
file in your project root and either edit or add this to your schema:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"your_project_name": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"standalone": true
}
},
...
}
...
}
...
}
And that’s it! Any further ng generate component pizza
commands no longer need the --standalone
flag and will use the rules you’ve setup.
🚀 Want to learn even more awesome Angular practices?
Check out my new Angular Courses if you’re serious about taking your skills to the top! There’s so much about Standalone Components and all the new best practices in the course.
Thanks for reading, happy coding!