Angular Guides Notes
Angular
Angular is framework that is developed and maintained by google.It is powerful, full-featured framework for building large-scale, structured frontend applications, especially useful in enterprise-level projects.
Core Foundation
a.Components
b.Services
c.Data Binding
d.Templates
e.Routes
g.Life Cycle Hooks
a.Component
A component is the fundamental building block of every Angular UI. Each one owns a slice of the screen and is defined by three things working together: a TypeScript class (the logic), an HTML template (the view), and CSS styles (the appearance). The decorator @Component wires them together and tells Angular where to render the component via its selector.
Components communicate with each other through @Input() (data flowing in from a parent) and @Output() with EventEmitter (events flowing out to a parent). This creates a clear, predictable data flow through the component tree.
Here's how the structure looks:
In code:
Directives:
Directives are instructions in Angular that modify the structure or behavior of elements in the DOM (HTML).
Angular has 3 main types of directives:
1.Component Directive:
A component is actually a directive with a template.
2. Structural Directives:
These change the structure of the DOM (add/remove elements).
Structural Directives are :
*ngIf
<div *ngIf="isLoggedIn">
Welcome User
</div>
*ngFor
<li *ngFor="let item of items">{{ item }}
</li>
<div [ngSwitch]="role">
<p *ngSwitchCase="'admin'">Admin Panel</p>
<p *ngSwitchCase="'user'">User Panel</p>
</div>
3. Attribute Directives
These change the appearance or behavior of an element.
Attribute directives are:
1. ngClass
<div [ngClass]="{'active': isActive}">
Hello
</div>
2. ngStyle
<div [ngStyle]="{'color': 'red', 'font-size': '20px'}">
Styled Text
</div>
4.Custom Directives:
You can create your own directive:
CLI: ng generate directive highlight
Eg. :
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Template:
<p appHighlight>
Highlighted Text
</p>
DECORATOR:
a decorator is a special TypeScript feature used to add metadata (extra information) to classes, methods, properties, or parameters.A decorator is written using @ and placed above a class or property.It tells Angular how something should behave.
eg:its an Component Decorator
@Component({
selector: 'app-root',
template: `<h1>Hello</h1>`
})
export class AppComponent {}
Common Angular Decorators
1. @Component
- Defines a component
- Links HTML, CSS, and logic
import { Component } from '@angular/core';
@Component({
selector: 'app-hello', // <app-hello> tag in HTML
template: `<h1>Hello, Angular!</h1>`, // HTML to render
styles: [`h1 { color: blue; }`] // CSS for this component
})
export class HelloComponent { }
2. @NgModule
It is a decorator that marks a class as an Angular module — the fundamental building block for organizing an Angular application.- Defines a module
- Groups components, services, etc.
Declarations: Components, directives, and pipes that belong to this moduleImports: Other modules whose exported classes are needed hereExports:Declarations: this module makes available to other modulesProviders: Services registered in this module's dependency injectorBootstrap:The root component to launch (root module only)declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [AppComponent]
})
export class AppModule {}
AppModule — which bootstraps the app3. @Injectable
It is a decorator that marks a class as available to Angular's dependency injection (DI) system — making it possible for Angular to create and inject instances of that class wherever they're needed.- Marks a class as a service
- Enables Dependency Injection (DI)
@Injectable({ providedIn: 'root' })
export class UserService {
getUsers()
{ return [...]; }
}
components or services where it is injected.
@Component({ ... })
export class UserListComponent {
constructor(private userService: UserService) {
}
}
NOTE: providedIn: 'root'
This is the most important config property. It controls where the service is registered:
'root' : | Single shared instance across the whole app (most common) |
'platform' : | Shared across multiple Angular apps on the same page |
'any' : | Separate instance per lazy-loaded module |
SomeModule : | Scoped to a specific module |
SomeComponent : | Scoped to a specific component (use component's providers array instead) |
4.@Input
@Input is a decorator that lets a parent component pass data down to a child component — it's Angular's primary mechanism for one-way data binding between components.Pass data from parent → child component
Eg:
@Component({
selector: 'app-user-card',
template: `<h2>{{ name }}</h2>`
})
export class UserCardComponent {
@Input() name: string = '';
@Input() age: number = 0;
}
Parents Template:
<app-user-card [name]="'Alice'" [age]="30" />
<app-user-card [name]="user.name" [age]="user.age" />
5. @Output
@Output is a decorator that lets a child component emit events up to a parent component — the counterpart to @Input@Component({
selector: 'app-counter',
<app-counter (countChanged)="onCountChanged($event)" />
( ) parentheses indicate event binding — the expression runs when the event fires.EventEmitter is Angular's wrapper around RxJS Subject. The generic type T is the payload type:typescript
@Output() selected = new EventEmitter<User>(); // emits an object @Output() deleted = new EventEmitter<string>(); // emits an id @Output() toggled = new EventEmitter<boolean>(); // emits a flag @Output() cleared = new EventEmitter<void>(); // emits nothingtransform data in templates (HTML) without changing the original value in your
PIPES :
It is used to
component.
Example:
{{ name | uppercase }}
Angular pipes are mainly classified into two types:
1. Built-in Pipes
These are provided by Angular by default.
eg:
1. UpperCasePipe →uppercase2. LowerCasePipe →lowercase3. DatePipe →date4. CurrencyPipe →currency5. DecimalPipe →number6. PercentPipe →percent7. SlicePipe →slice8. JsonPipe →json9. AsyncPipe →async
2. Custom Built Pipes
These are user-defined pipes created for specific logic.
from cli ng generate pipe myPipe
eg
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
in Template :{{ 'hello' | reverse }}Based on classification there are two types of pipes
1. pure pipes2. Impure pipes1.Pure Pipes:A pure pipe is a pipe that runs only when the input value changes (by reference or primitivevalue).
This is the default behavior for all Angular pipes.Angular checks:
- Primitive change → ✅ runs pipe
- Object/array reference change → ✅ runs pipe
- Internal mutation (same reference) → ❌ does NOT run pipe
@Pipe({
name: 'double'
})
export class DoublePipe implements PipeTransform {
transform(value: number): number {
console.log('Pipe executed');
return value * 2;
}
}{{ count | double }}2. Impure Pipes:An impure pipe is a pipe that runs on every change detection cycle, regardless of whether
the input value changed or not.To make a pipe impure, you explicitly set@Pipe({
name: 'example',
pure: false
})
Impure pipes execute when:
- Component updates (any event)
- User interaction happens
- Timer/async updates occur
- Even if input data did NOT change
Comments
Post a Comment