Basics
Angular CLI Commands
Essential commands for Angular development:
// Create a new project ng new my-app // Serve the application ng serve --open // Generate component ng generate component components/my-component // Generate service ng generate service services/my-service // Build for production ng build --configuration production
Component Anatomy
Structure of a basic Angular component:
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-my-component', template: ` <div class="container"> <h2>{{ title }}</h2> <button (click)="handleClick()">Click Me</button> </div> `, styles: [` .container { padding: 20px; } `] }) export class MyComponent { @Input() title: string = 'Default Title'; @Output() buttonClicked = new EventEmitter<string>(); handleClick() { this.buttonClicked.emit('Button clicked!'); } }
Dependency Injection
How to inject services into components:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { getData() { return ['item1', 'item2', 'item3']; } } // In your component export class MyComponent { constructor(private dataService: DataService) {} items = this.dataService.getData(); }
Template Syntax
Common template binding techniques:
<!-- Interpolation --> <p>{{ message }}</p> <!-- Property binding --> <img [src]="imageUrl" [alt]="imageAlt" /> <!-- Event binding --> <button (click)="onClick($event)">Click</button> <!-- Two-way binding --> <input [(ngModel)]="userName" /> <!-- Attribute binding --> <button [attr.aria-label]="buttonLabel">Submit</button>
Common Directives
Essential structural and attribute directives:
<!-- Conditional rendering (OLD) --> <div *ngIf="isVisible">Visible content</div> <!-- Loop through array (OLD) --> <ul> <li *ngFor="let item of items">{{ item }}</li> </ul> <!-- Switch statement (OLD) --> <div [ngSwitch]="status"> <div *ngSwitchCase="'active'">Active</div> <div *ngSwitchDefault>Inactive</div> </div> <!-- Apply CSS class conditionally --> <div [ngClass]="{'active': isActive, 'disabled': isDisabled}"></div>