Learn
Cheatsheet
Angular
Components, templates, and directives at a glance.
Component Structure
| @Component({ selector, template }) | Component decorator |
| selector: "app-foo" | Custom HTML element name |
| templateUrl: "./foo.component.html" | External template file |
| styleUrls: ["./foo.component.css"] | Component-scoped styles |
| export class FooComponent { } | Component class |
Template Syntax
| {{ expression }} | Interpolation — render value as text |
| [property]="value" | Property binding: component to DOM |
| (event)="handler()" | Event binding: DOM to component |
| [(ngModel)]="prop" | Two-way binding (requires FormsModule) |
| [class.active]="expr" | Conditionally add a CSS class |
| [style.color]="expr" | Conditionally set inline style |
Built-in Directives
| *ngIf="condition" | Render element only when true |
| *ngFor="let x of list" | Repeat template for each item |
| *ngFor="...; let i = index" | Access loop index |
| [ngClass]="{ cls: bool }" | Apply classes from an object |
| [ngStyle]="{ color: val }" | Apply styles from an object |
Services & DI
| @Injectable({ providedIn: "root" }) | Singleton service across the app |
| constructor(private svc: MyService) | Inject service via constructor |
| this.http.get<T>(url) | HTTP GET — returns Observable |
| .subscribe(data => ...) | Subscribe to an Observable |
Component Communication
| @Input() prop: string | Receive data from parent |
| @Output() ev = new EventEmitter() | Declare event for parent to handle |
| this.ev.emit(value) | Trigger the output event |
| <child [prop]="val" (ev)="fn($event)"> | Parent: bind input and handle output |
| value | pipeName | Transform value in template |