Module 1: Getting Started with Angular CLI
What is Angular CLI?
Angular CLI (Command Line Interface) is a tool that automates common development tasks in Angular projects, such as generating components, services, modules, and building or testing applications. It enforces best practices and simplifies workflows, making it a must-have for Angular developers.
Why Use Angular CLI?
Productivity: Automates repetitive tasks like scaffolding and configuration.
Consistency: Ensures standardized project structure and coding practices.
Ease of Use: Simplifies complex tasks like building and deploying.
Community Support: Regularly updated with Angular’s ecosystem.
Pros:
Saves time with automated scaffolding.
Integrates seamlessly with Angular’s ecosystem.
Built-in support for testing and optimization.
Cons:
Can feel restrictive for developers who prefer manual control.
Learning curve for advanced commands.
May generate boilerplate code that needs cleanup.
Alternatives:
Manual setup with Webpack or Vite.
Other frameworks’ CLIs (e.g., Vue CLI, React’s Create React App).
Best Practices:
Always install the latest stable version of Angular CLI (npm install -g @angular/cli).
Use Angular CLI in a version-controlled project to track changes.
Familiarize yourself with command flags to customize outputs.
Installing Angular CLI
To get started, install Angular CLI globally:
npm install -g @angular/cli
Verify the installation:
ng version
Example: Create a new Angular project called my-app:
ng new my-app
This command scaffolds a new Angular project with a standard structure, including src/, angular.json, and package.json.
Interactive Tip: When running ng new, Angular CLI prompts you to choose options like adding routing or selecting a stylesheet format (e.g., CSS, SCSS). For beginners, choose CSS and skip routing to keep things simple.
Module 2: Generating Components and Other Artifacts
Generating Components
Components are the building blocks of Angular applications. The ng generate (or ng g) command creates components, services, modules, and more.
Command:
ng generate component my-component
# or
ng g c my-component
This creates a my-component folder with:
my-component.component.ts
my-component.component.html
my-component.component.css
my-component.component.spec.ts
Real-World Example: Imagine you’re building an e-commerce app, and you need a product card component.
ng g c components/product-card
This generates a product-card component in the src/app/components folder. Update the component to display product details:
// src/app/components/product-card/product-card.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-product-card',
templateUrl: './product-card.component.html',
styleUrls: ['./product-card.component.css']
})
export class ProductCardComponent {
@Input() product: { name: string, price: number, image: string };
}
<!-- src/app/components/product-card/product-card.component.html -->
<div class="card">
<img [src]="product.image" alt="{{ product.name }}">
<h3>{{ product.name }}</h3>
<p>${{ product.price }}</p>
<button>Add to Cart</button>
</div>
Pros:
Fast scaffolding with consistent structure.
Automatically updates the parent module’s declarations.
Supports inline templates and styles with flags (e.g., --inline-template).
Cons:
May generate unnecessary files (e.g., spec files) if not needed.
Limited customization during generation.
Alternatives:
Manually create components (not recommended due to time cost).
Use third-party tools like Nx for advanced scaffolding.
Best Practices:
Use descriptive names (e.g., product-card instead of card).
Organize components in a components/ folder for clarity.
Use --module to specify which module to register the component in for large apps.
Advanced Scenario: Generate a component with specific options, like skipping tests and using SCSS:
ng g c shared/footer --skip-tests --style=scss
This creates a footer component in the shared folder without a spec file and with SCSS for styling.
Module 3: Building Angular Applications
Building for Development and Production
The ng build command compiles your Angular app into an output directory (dist/ by default).
Command:
ng build
For production, use the --prod flag to optimize the build:
ng build --prod
Real-World Example: You’re preparing an Angular app for a client demo. Run a development build to test locally:
ng build
Then, serve the app using a local server (e.g., http-server or Angular’s ng serve):
ng serve
For production, optimize the build with minification and tree-shaking:
ng build --prod --output-path=dist/my-app
Pros:
Fast builds for development.
Production builds are highly optimized (minified, tree-shaken).
Supports differential loading for modern browsers.
Cons:
Production builds can be slow for large apps.
Limited control over Webpack configuration without ejecting.
Alternatives:
Use Webpack directly for custom builds.
Use Vite for faster builds in smaller projects.
Best Practices:
Use --watch during development to rebuild on changes.
Enable Ahead-of-Time (AOT) compilation for production (--aot).
Regularly clean the dist/ folder to avoid stale files.
Advanced Scenario: Optimize a production build with source maps for debugging:
ng build --prod --source-map
This generates source maps alongside minified files, useful for debugging production issues.
Module 4: Testing Angular Applications
Running Tests
Angular CLI integrates with Jasmine and Karma for unit testing and Protractor for end-to-end (E2E) testing.
Unit Testing:
ng test
This runs unit tests defined in *.spec.ts files using Karma.
E2E Testing:
ng e2e
This runs E2E tests using Protractor.
Real-World Example: You’re building a login component and want to ensure it works correctly. Generate a component with a test file:
ng g c login
The generated login.component.spec.ts includes basic tests. Add a test to verify the login button is disabled when the form is invalid:
// src/app/login/login.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
import { FormsModule } from '@angular/forms';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [LoginComponent],
imports: [FormsModule]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should disable login button when form is invalid', () => {
const button = fixture.nativeElement.querySelector('button');
component.form = { valid: false };
fixture.detectChanges();
expect(button.disabled).toBeTruthy();
});
});
Run the tests:
ng test
Pros:
Built-in support for Jasmine, Karma, and Protractor.
Code coverage reports with --code-coverage.
Easy integration with CI/CD pipelines.
Cons:
Karma can be slow for large test suites.
Protractor is deprecated; alternatives like Cypress are gaining popularity.
Test setup can be complex for beginners.
Alternatives:
Use Jest for faster unit testing.
Use Cypress or Playwright for modern E2E testing.
Best Practices:
Write tests for all critical components and services.
Use --code-coverage to ensure sufficient test coverage.
Mock external dependencies to isolate tests.
Advanced Scenario: Run tests with code coverage and open the report:
ng test --code-coverage
The coverage report is generated in the coverage/ folder. Open index.html in a browser to view it.
Module 5: Deploying Angular Applications
Deploying to Production
The ng build --prod command prepares your app for deployment. You can deploy the output to platforms like Firebase, Netlify, or AWS.
Command:
ng build --prod
Real-World Example: Deploy an Angular app to Firebase Hosting.
Install Firebase CLI:
npm install -g firebase-tools
Log in to Firebase:
firebase login
Initialize Firebase Hosting in your project:
firebase init hosting
Build the Angular app:
ng build --prod
Deploy to Firebase:
firebase deploy
Pros:
Simple deployment with platforms like Firebase and Netlify.
Optimized builds ensure fast load times.
Supports server-side rendering (SSR) with Angular Universal.
Cons:
Deployment requires familiarity with hosting platforms.
Large apps may require additional optimization (e.g., lazy loading).
Alternatives:
Deploy to Netlify, Vercel, or AWS S3.
Use Angular Universal for SSR to improve SEO.
Best Practices:
Use lazy loading for large apps to reduce initial bundle size.
Configure base-href for deployments to subdirectories:
ng build --prod --base-href=/my-app/
Test the production build locally before deploying.
Advanced Scenario: Deploy with lazy-loaded modules for better performance. Generate a feature module:
ng g module dashboard --route dashboard --module app
This creates a dashboard module with lazy loading configured in app-routing.module.ts:
// src/app/app-routing.module.ts
const routes: Routes = [
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
];
Build and deploy the optimized app:
ng build --prod
firebase deploy
Module 6: Advanced Angular CLI Commands
Generating Services, Modules, and More
Beyond components, Angular CLI can generate services, pipes, directives, and guards.
Service Example:
ng g service services/auth
This creates an auth.service.ts file. Use it to handle authentication:
// src/app/services/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {}
login(credentials: { username: string, password: string }): Observable<any> {
return this.http.post('/api/login', credentials);
}
}
Module Example:
ng g module admin --routing
This creates an admin module with a routing file.
Pros:
Speeds up development of complex features.
Ensures consistent file structure.
Cons:
May generate unused files (e.g., routing files).
Advanced features require manual configuration.
Best Practices:
Use --flat to generate files without a folder (e.g., for small services).
Combine with --module to register in specific modules.
Advanced Scenario: Generate a guard for route protection:
ng g guard guards/auth
Choose CanActivate and implement the guard:
// src/app/guards/auth/auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../services/auth/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
Use the guard in routing:
// src/app/app-routing.module.ts
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];
Module 7: Best Practices and Standards for Angular CLI
Best Practices
Organize Files: Group related files in folders (e.g., components/, services/).
Use Flags: Leverage CLI flags like --skip-tests or --style=scss to customize generation.
Lazy Loading: Implement lazy loading for large apps to improve performance.
Linting: Run ng lint to enforce coding standards.
Update Regularly: Keep Angular CLI updated (ng update) to avoid compatibility issues.
Standards
Follow Angular’s style guide (e.g., prefix component selectors with app-).
Use TypeScript strict mode for type safety.
Maintain a clean angular.json configuration for builds.
Example: Enforce linting with ESLint:
ng add @angular-eslint/schematics
ng lint
This sets up ESLint and runs linting checks.
Conclusion
Mastering Angular CLI commands is a game-changer for Angular developers. From generating components to building, testing, and deploying apps, the CLI simplifies complex tasks and enforces best practices.
No comments:
Post a Comment
Thanks for your valuable comment...........
Md. Mominul Islam