Angular
104 challenges · 0 mastered
A Directive is a class that changes the behavior, structure, or appearance of DOM elements.
<div *ngIf='isLoggedIn'>Welcome</div>Directives tell Angular what to do with HTML elements.
Angular has three main types of directives: Component Directives, Structural Directives, and Attribute Directives.
Component -> @Component
Structural -> *ngIf, *ngFor
Attribute -> ngClass, ngStyleStructural directives change the DOM, while attribute directives modify existing elements.
Structural Directives add, remove, or manipulate DOM elements. Common examples are *ngIf, *ngFor, and *ngSwitch.
<div *ngIf='isAdmin'>Admin Panel</div>
<li *ngFor='let product of products'>{{product}}</li>Structural directives decide what appears on the page.
Attribute Directives modify the appearance or behavior of existing DOM elements without adding or removing them.
<div [ngClass]="{'active': isSelected}">Product</div>
<div [ngStyle]="{'color':'red'}">Error</div>Attribute directives change how an element looks or behaves.
ngIf removes or adds elements to the DOM, while hidden only hides the element but keeps it in the DOM.
<div *ngIf='showContent'>Content</div>
<div [hidden]='!showContent'>Content</div>ngIf removes the chair from the room. hidden covers the chair with a cloth.
A Pipe is used to transform data in Angular templates before displaying it to the user. Pipes only change how data is displayed and do not modify the original value stored in the component.
{{ name | uppercase }}
{{ amount | currency:'INR' }}
{{ today | date:'dd/MM/yyyy' }}Think of a pipe as a display filter. The original data stays the same, but Angular shows it in a different format.
Angular provides several built-in pipes such as uppercase, lowercase, date, currency, percent, number, and slice.
{{ name | uppercase }}
{{ amount | currency:'INR' }}
{{ 0.75 | percent }}
{{ today | date:'dd/MM/yyyy' }}Instead of manually formatting data in TypeScript, Angular pipes format it directly in the template.
A Custom Pipe is a pipe created by developers when Angular's built-in pipes do not satisfy a business requirement. It helps keep formatting logic reusable and centralized.
@Pipe({name:'capitalize'})
export class CapitalizePipe implements PipeTransform {
transform(value:string){
return value.charAt(0).toUpperCase() + value.slice(1);
}
}If you need to format user names in many places, create one custom pipe and reuse it everywhere.
Custom Pipes improve reusability, keep templates cleaner, and separate formatting logic from business logic. Updating the pipe updates behavior everywhere it is used.
{{ product.price | customCurrency }}If currency formatting changes from Rupees to Dollars, update the pipe once instead of changing every component.
Pipes transform data for display. Directives change the DOM's structure, appearance, or behavior.
{{ name | uppercase }}
<div *ngIf='isLoggedIn'>Welcome</div>Pipe changes the data. Directive changes the HTML.
A Service is a reusable class that contains business logic, API calls, shared state, or utility methods. Services help keep components clean and promote code reusability.
@Injectable({providedIn:'root'})
export class UserService {
getUsers() {
return this.http.get('/api/users');
}
}Instead of writing API calls in every component, create them once in a service and reuse them everywhere.
Services help centralize business logic, improve code reusability, reduce duplicate code, and keep components focused on UI logic.
constructor(private userService: UserService) {}Think of a service as a common helper that multiple components can use.
Dependency Injection is a design pattern where Angular automatically creates and provides required dependencies to a class instead of the class creating them manually.
constructor(private productService: ProductService) {}Instead of cooking your own food, a waiter brings it to your table. Angular provides the service instead of the component creating it.
A dependency is any service or object that a class needs to function.
constructor(private userService: UserService) {}If ProductComponent needs ProductService, then ProductService is its dependency.
Angular creates a single shared instance of the service for the entire application. This is known as a Singleton Service.
@Injectable({providedIn:'root'})One service instance shared across all components.
@Input is used for parent-to-child communication. It allows a parent component to pass data to a child component.
// Parent
<app-user [userName]='userName'></app-user>
// Child
@Input() userName: string = '';Parent passes data down to child like a parent handing a child their lunchbox.
@Output is used for child-to-parent communication. It allows a child component to notify or send data to its parent component using EventEmitter.
// Child
@Output() saved = new EventEmitter<string>();
// Parent
<app-form (saved)='onSave($event)'></app-form>A child component emits a save event when a button is clicked.
EventEmitter is used with @Output to emit events or data from a child component to its parent component.
@Output() saveClicked = new EventEmitter<UserData>();
onSave() {
this.saveClicked.emit(this.userData);
}saveClicked.emit(userData) fires the event up to the parent.
A shared service can be used to store and share data between unrelated components.
@Injectable({providedIn:'root'})
export class SharedDataService {
user$ = new BehaviorSubject<User|null>(null);
}NavbarComponent and ProfileComponent can access the same UserService.
Lifecycle Hooks are methods that Angular calls during different stages of a component's life, from creation to destruction.
ngOnInit() {}
ngOnChanges() {}
ngOnDestroy() {}Angular notifies you when a component starts, updates, and ends.
ngOnInit runs after Angular initializes the component. It is commonly used for API calls and initialization logic.
ngOnInit() {
this.loadProducts();
}Component is ready, now load data.
ngOnDestroy runs before a component is removed from the DOM. It is commonly used to clean up subscriptions, intervals, and event listeners.
ngOnDestroy() {
this.subscription.unsubscribe();
}Clean up before leaving the component.
ngAfterViewInit runs after Angular has fully initialized the component view and child views.
@ViewChild('input') input!: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}The HTML is ready, now safely access DOM elements.
Unsubscribing prevents memory leaks and unnecessary processing when a component is destroyed.
ngOnDestroy() {
this.subscription.unsubscribe();
}Stop listening when you no longer need updates.
