`FormArray` is used to manage a collection of form controls in Angular reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
Lazy loading is implemented using Angular's routing module by defining routes with a loadChildren property.
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
HTTP errors can be handled using Angular's `HttpInterceptor` to catch and process HTTP errors globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
// Handle error
console.error('HTTP Error:', error);
return throwError(error);
})
);
}
}
`@ContentChildren` allows querying of projected content in Angular.
import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements AfterContentInit {
@ContentChildren(ChildComponent) children: QueryList;
ngAfterContentInit() {
console.log(this.children.toArray());
}
}
The `ngIf` directive can be used with `else` to conditionally display alternate content.
@Component({
selector: 'app-example',
template: `
Content is visible
Content is not visible
`,
})
export class ExampleComponent {
isVisible = true;
}
The `trackBy` function is used to optimize the rendering of lists by tracking changes to items in the list.
@Component({
selector: 'app-example',
template: `
{{ item.name }}
`,
})
export class ExampleComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackById(index: number, item: any) {
return item.id;
}
}
A custom pipe is created to transform data in the template.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
`@HostListener` allows listening to events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
Form validation can be handled using Angular's reactive forms and built-in validators.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`,
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `@Inject` decorator is used to specify the provider to be injected into a class.
import { Injectable, Inject } from '@angular/core';
import { API_URL } from './tokens';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) { }
}
Custom error handling can be implemented using Angular's `HttpInterceptor` to catch and handle HTTP errors.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class CustomErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
// Custom error handling logic
console.error('An error occurred:', error.message);
return throwError(error);
})
);
}
}
A reusable component is created by defining it with a selector and providing inputs and outputs.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-reusable',
template: `
`,
})
export class ReusableComponent {
@Input() label: string;
@Output() clicked = new EventEmitter();
onClick() {
this.clicked.emit();
}
}
Dependency Injection is used to inject services or other dependencies into components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
Application state can be managed using services, or state management libraries like NgRx or Akita.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StateService {
private state = new BehaviorSubject({});
state$ = this.state.asObservable();
setState(newState: any) {
this.state.next(newState);
}
}
Build and deployment settings are configured in the `angular.json` file.
{
"projects": {
"my-app": {
"architect": {
"build": {
"options": {
"outputPath": "dist/my-app",
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "tsconfig.app.json"
}
}
}
}
}
}
Route guards are used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(): boolean {
// Check authentication status
const isAuthenticated = false;
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
`HttpClient` is used for making HTTP requests to a backend API.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data');
}
}
Services are used to share data and logic across multiple components.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
`@Input` is used to pass data to a child component, and `@Output` is used to emit events from a child component.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Input() data: string;
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit('Notification from child');
}
}
`@ViewChild` is used to access a child component or DOM element from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `Paragraph
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild('paragraph') paragraph: ElementRef;
ngAfterViewInit() {
console.log(this.paragraph.nativeElement.textContent);
}
}
The `ngSwitch` directive is used to conditionally display one of several elements based on the value of an expression.
@Component({ selector: 'app-switch', template: `
Case A
Case B
Default case
`, }) export class SwitchComponent { value = 'A'; }
Custom directives can be created to modify the behavior or appearance of elements.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) { }
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
HTTP interceptors are used to modify HTTP requests and responses.
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
]
})
export class AppModule { }
The `@HostBinding` decorator binds a property of the host element to a property of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appClass]'
})
export class ClassDirective {
@HostBinding('class.active') isActive = true;
}
The `@ViewChildren` decorator is used to query for multiple elements or directives in the template.
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(ChildComponent) childComponents: QueryList;
ngAfterViewInit() {
console.log(this.childComponents.toArray());
}
}
Asynchronous operations can be handled using RxJS observables and operators.
import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-data', template: `
{{ data | json }}
`, }) export class DataComponent implements OnInit { data$ = this.apiService.getData(); constructor(private apiService: ApiService) { } ngOnInit() { } }
The `@ContentChild` decorator allows querying for a single projected content element.
import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterContentInit {
@ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
console.log(this.child);
}
}
The `ngClass` directive is used to add or remove CSS classes dynamically.
@Component({ selector: 'app-example', template: `
Conditional classes
`, }) export class ExampleComponent { isActive = true; toggle() { this.isActive = !this.isActive; } }
The `ngModel` directive is used for two-way data binding between the form control and the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
{{ value }}
`, }) export class TwoWayBindingComponent { value = 'Initial value'; }
The `@Injectable` decorator marks a class as a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return ['Data 1', 'Data 2'];
}
}
The `Router` service is used to programmatically navigate between routes.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: `
`,
})
export class NavigateComponent {
constructor(private router: Router) { }
goToHome() {
this.router.navigate(['/home']);
}
}
Route resolvers are used to fetch data before navigating to a route.
import { Injectable } from '@angular/core';
import { Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
@Injectable({
providedIn: 'root'
})
export class DataResolver implements Resolve {
constructor(private apiService: ApiService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
return this.apiService.getData();
}
}
Dynamic form controls can be created using Angular's `FormBuilder` service.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
dynamicControl: ['']
});
}
}
The `trackBy` function improves performance by tracking items by their identity.
@Component({
selector: 'app-list',
template: `
{{ item.name }}
`,
})
export class ListComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
The `ngIf` directive can conditionally display elements with an `else` block.
@Component({ selector: 'app-condition', template: `
Visible
Not visible `, }) export class ConditionComponent { isVisible = true; }
`HttpClient` is used for making POST requests to a backend API.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
postData(data: any) {
return this.http.post('https://api.example.com/data', data);
}
}
The `FormArray` is used to manage an array of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form-array',
template: `
`,
})
export class DynamicFormArrayComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
items: this.fb.array([this.fb.control('')])
});
}
get items() {
return this.formGroup.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
The `ngOnDestroy` lifecycle hook is used to clean up resources when a component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-cleanup', template: `
Cleanup example
`, }) export class CleanupComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { this.subscription.unsubscribe(); } }
The `ng-template` directive defines a template that can be reused or rendered conditionally.
@Component({ selector: 'app-template', template: `
{{ data }}
`, }) export class TemplateComponent { }
The `trackBy` function helps Angular track items in a list and improve rendering performance.
@Component({
selector: 'app-track-by',
template: `
{{ item.name }}
`,
})
export class TrackByComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
The `@ViewChild` decorator can be used with a static flag to determine when the query should be resolved.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent, { static: true }) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
The `let` syntax in `ngFor` allows you to define a variable for each item in the loop.
@Component({
selector: 'app-list',
template: `
-
{{ i + 1 }}: {{ item }}
`,
})
export class ListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `@Input` decorator is used to pass data from a parent component to a child component, while the `@Output` decorator is used to emit events from the child to the parent.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`,
})
export class ChildComponent {
@Input() data: string;
@Output() notify = new EventEmitter();
notifyParent() {
this.notify.emit('Data from child');
}
}
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent {
parentData = 'Data from parent';
handleNotification(message: string) {
console.log(message);
}
}
The `@ContentChildren` decorator queries for multiple projected content elements in a component.
import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterContentInit {
@ContentChildren(ChildComponent) children: QueryList;
ngAfterContentInit() {
this.children.forEach(child => console.log(child));
}
}
`FormGroup` and `FormControl` are used to create and manage reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
The `FormBuilder` service simplifies form creation and validation in Angular forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-builder-form',
template: `
`,
})
export class BuilderFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
email: ['']
});
}
}
The `Validators` class provides built-in validation functions for forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validate-form',
template: `
`,
})
export class ValidateFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
Lazy loading allows modules to be loaded on demand, improving application performance.
const routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Form submission in reactive forms can be handled by subscribing to the form's `valueChanges` or `statusChanges` observable.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
name: ['']
});
this.formGroup.valueChanges.subscribe(value => {
console.log('Form value changed:', value);
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
An `HttpInterceptor` can be used to modify HTTP requests or responses globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedReq = req.clone({
setHeaders: {
Authorization: `Bearer your-token`
}
});
return next.handle(clonedReq);
}
}
Route guards can be used to control access to routes based on certain conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isLoggedIn = false; // Replace with actual login check
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Custom directives can be created to extend HTML elements with additional behavior.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
The `ChangeDetectorRef` service allows you to manually control change detection.
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-manual-detection',
template: `{{ message }}
`,
})
export class ManualDetectionComponent {
message = 'Initial message';
constructor(private cdRef: ChangeDetectorRef) {}
updateMessage() {
this.message = 'Updated message';
this.cdRef.detectChanges();
}
}
The `EventEmitter` class is used to emit custom events from child components to parent components.
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Output() event = new EventEmitter();
sendEvent() {
this.event.emit('Data from child');
}
}
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent {
handleEvent(message: string) {
console.log(message);
}
}
Feature modules allow you to organize application functionality into cohesive blocks.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
declarations: [FeatureComponent],
imports: [CommonModule],
exports: [FeatureComponent]
})
export class FeatureModule { }
The `NgZone` service helps control Angular's change detection process manually.
import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-zone',
template: `{{ message }}
`,
})
export class ZoneComponent {
message = 'Initial message';
constructor(private ngZone: NgZone) {
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.message = 'Updated message';
this.ngZone.run(() => console.log('Change detected'));
}, 1000);
});
}
}
The `@HostListener` decorator allows you to listen to DOM events directly on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('Element clicked:', event);
}
}
The `@ViewChildren` decorator queries for multiple elements within the view of a component.
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(ChildComponent) children: QueryList;
ngAfterViewInit() {
this.children.forEach(child => console.log(child));
}
}
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-changes',
template: `{{ inputValue }}
`,
})
export class ChangesComponent implements OnChanges {
@Input() inputValue: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Changes:', changes);
}
}
The `ngOnInit` lifecycle hook is used for component initialization logic.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-init',
template: `Component initialized
`,
})
export class InitComponent implements OnInit {
ngOnInit() {
console.log('Component initialized');
}
}
The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component destroyed
`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { // Unsubscribe to avoid memory leaks if (this.subscription) { this.subscription.unsubscribe(); } } }
The `ngModel` directive is used for two-way data binding between form controls and component properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
Value: {{ value }}
`, }) export class TwoWayBindingComponent { value: string = ''; }
The `@HostBinding` decorator is used to bind a property of the host element to a property of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlight') isHighlighted = true;
}
The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('Element clicked:', event);
}
}
The `ngOnChanges` lifecycle hook responds to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-changes', template: `
{{ inputValue }}
`, }) export class ChangesComponent implements OnChanges { @Input() inputValue: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
The `ngOnInit` lifecycle hook is used for component initialization logic.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
Component initialized
`, }) export class InitComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
The `ngAfterViewInit` lifecycle hook is used after the component's view and child views have been initialized.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-init', template: `
Content
`, }) export class ViewInitComponent implements AfterViewInit { @ViewChild('myDiv') div: ElementRef; ngAfterViewInit() { console.log(this.div.nativeElement.textContent); } }
The `ngAfterContentInit` lifecycle hook is used after Angular initializes the content of the component.
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-init',
template: ` `,
})
export class ContentInitComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `ngAfterViewChecked` lifecycle hook is used after Angular checks the component's view and child views.
import { Component, AfterViewChecked } from '@angular/core'; @Component({ selector: 'app-view-checked', template: `
Check view
`, }) export class ViewCheckedComponent implements AfterViewChecked { ngAfterViewChecked() { console.log('View checked'); } }
The `ngAfterContentChecked` lifecycle hook is used after Angular checks the content projected into the component.
import { Component, AfterContentChecked } from '@angular/core'; @Component({ selector: 'app-content-checked', template: `
Check content
`, }) export class ContentCheckedComponent implements AfterContentChecked { ngAfterContentChecked() { console.log('Content checked'); } }
The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component destroyed
`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { // Unsubscribe to avoid memory leaks if (this.subscription) { this.subscription.unsubscribe(); } } }
The `@Input` decorator allows data to be passed from a parent component to a child component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}
`, }) export class ChildComponent { @Input() data: string; } @Component({ selector: 'app-parent', template: `
`, }) export class ParentComponent { parentData = 'Data from parent'; }
The `@Output` decorator is used to emit events from a child component to a parent component.
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ``, }) export class ChildComponent { @Output() dataEvent = new EventEmitter
(); sendData() { this.dataEvent.emit('Data from child'); } } @Component({ selector: 'app-parent', template: `
{{ receivedData }}
`, }) export class ParentComponent { receivedData: string; receiveData(data: string) { this.receivedData = data; } }
The `@ViewChild` decorator allows querying a single element or directive from the component's view.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Content
`, }) export class ViewChildComponent implements AfterViewInit { @ViewChild('myDiv') div: ElementRef; ngAfterViewInit() { console.log(this.div.nativeElement.textContent); } }
A shared module allows you to share common functionality across multiple modules.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';
@NgModule({
declarations: [SharedComponent],
imports: [CommonModule],
exports: [SharedComponent]
})
export class SharedModule { }
Routing configuration is done in the `@NgModule` decorator with the `RouterModule.forRoot` method.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The `ActivatedRoute` service provides access to the route parameters of the active route.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route', template: `
Parameter: {{ param }}
`, }) export class RouteComponent implements OnInit { param: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.param = params.get('id'); }); } }
The `Router` service allows you to navigate programmatically to different routes.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``,
})
export class NavigationComponent {
constructor(private router: Router) {}
navigate() {
this.router.navigate(['/about']);
}
}
The `FormControl` class is used to manage the value and validation status of form inputs.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form', template: `
Value: {{ nameControl.value }}
`, }) export class FormComponent { nameControl = new FormControl(''); }
The `FormArray` class is used to manage an array of form controls.
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`,
})
export class FormArrayComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([this.fb.control('')])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
Reactive forms allow you to create forms with validation using `FormControl` and `FormGroup` classes.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `FormBuilder` class helps create complex forms with nested controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-nested-form',
template: `
`,
})
export class NestedFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
address: this.fb.group({
street: [''],
city: ['']
})
});
}
}
You can create custom validators and use them with form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-custom-validation',
template: `
`,
})
export class CustomValidationComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
password: ['', [Validators.required, this.uppercaseValidator]]
});
}
uppercaseValidator(control) {
const hasUppercase = /[A-Z]/.test(control.value);
return hasUppercase ? null : { pattern: true };
}
}
Asynchronous validators are used to perform validation that requires an HTTP request or other async operations.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, AsyncValidatorFn, AbstractControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { debounceTime, map, catchError } from 'rxjs/operators';
@Component({
selector: 'app-async-validator',
template: `
`,
})
export class AsyncValidatorComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
username: ['', null, this.usernameValidator()]
});
}
usernameValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable => {
return of(control.value).pipe(
debounceTime(300),
map(value => value === 'admin' ? { taken: true } : null),
catchError(() => of(null))
);
};
}
}
The `HttpClient` service is used to perform HTTP requests.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-http', template: `
Data: {{ data | json }}
`, }) export class HttpComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const cloned = req.clone({
setHeaders: {
Authorization: 'Bearer my-token'
}
});
return next.handle(cloned);
}
}
The `HttpParams` class is used to build query parameters for HTTP requests.
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-http-params', template: `
Data: {{ data | json }}
`, }) export class HttpParamsComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { const params = new HttpParams().set('param1', 'value1').set('param2', 'value2'); this.http.get('https://api.example.com/data', { params }).subscribe(response => { this.data = response; }); } }
The `NgModel` directive is used for two-way data binding in Angular forms.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Name: {{ name }}
`, }) export class NgModelComponent { name: string = ''; }
Custom pipes allow you to transform data before displaying it in the template.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
The `@HostListener` decorator allows you to listen to DOM events in your component or directive.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
The `@ContentChild` decorator is used to access a single child element projected into a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-child',
template: ` `,
})
export class ContentChildComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `ChangeDetectorRef` service allows you to manually trigger change detection.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-detection', template: `
{{ message }}
`, }) export class DetectionComponent { message: string = 'Initial Message'; constructor(private cd: ChangeDetectorRef) {} updateMessage() { this.message = 'Updated Message'; this.cd.detectChanges(); } }
The `@Injectable` decorator is used to create a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item1', 'Item2', 'Item3'];
}
}
Providers can be configured in the `@NgModule` decorator to be available throughout the application or module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataService } from './data.service';
@NgModule({
imports: [CommonModule],
providers: [DataService]
})
export class SharedModule { }
The `ng-content` directive is used to project content into a component's template.
import { Component } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `,
})
export class ContentComponent { }
The `@Inject` decorator allows you to specify a dependency to be injected into a component or service.
import { Component, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-doc', template: `
Document title: {{ title }}
`, }) export class DocComponent { title: string; constructor(@Inject(DOCUMENT) private document: Document) { this.title = this.document.title; } }
The `@HostBinding` decorator is used to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}
The `@Host` decorator allows you to inject a dependency from the host element.
import { Directive, Host } from '@angular/core';
import { DataService } from './data.service';
@Directive({
selector: '[appHost]',
})
export class HostDirective {
constructor(@Host() private dataService: DataService) {
console.log(this.dataService.getData());
}
}
The `ngOnInit` lifecycle hook is used to perform initialization logic after Angular has initialized the component's data-bound properties.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
Component initialized
`, }) export class InitComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component or directive.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component is being destroyed
`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription = new Subscription(); ngOnDestroy() { this.subscription.unsubscribe(); } }
The `@ViewChild` decorator allows you to access a child component or element within the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Some text
`, }) export class ViewChildComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
The `@ContentChildren` decorator is used to access multiple child elements projected into a component.
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-children',
template: ` `,
})
export class ContentChildrenComponent implements AfterContentInit {
@ContentChildren('content') contents: QueryList;
ngAfterContentInit() {
this.contents.forEach(content => {
console.log(content.nativeElement.textContent);
});
}
}
The `ngOnChanges` lifecycle hook allows you to respond to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-changes', template: `
{{ value }}
`, }) export class ChangesComponent implements OnChanges { @Input() value: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
The `ngFor` directive is used to iterate over arrays or collections in Angular templates.
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for',
template: `
{{ item }}
`,
})
export class NgForComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngIf` directive conditionally includes or excludes elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-if', template: `
This is visible
`, }) export class NgIfComponent { isVisible = true; }
The `ngClass` directive is used to dynamically add or remove CSS classes based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-class', template: `
Conditional classes
`, }) export class NgClassComponent { isActive = true; }
The `ngStyle` directive allows you to apply inline styles conditionally based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-style', template: `
Styled text
`, }) export class NgStyleComponent { color = 'blue'; fontSize = '20px'; }
The `@Pipe` decorator is used to create custom pipes to transform data in templates.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
The `ngModel` directive is used for two-way data binding in Angular forms.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Name: {{ name }}
`, }) export class NgModelComponent { name: string = ''; }
Reactive forms provide a way to handle form submissions with more control over validation and state.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `FormBuilder` service is used to create form groups in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`,
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['']
});
}
}
The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer my-token')
});
return next.handle(authReq);
}
}
The `HttpClient` service provides methods to handle errors using RxJS operators.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Component({ selector: 'app-http-error', template: `
Check console for errors
`, }) export class HttpErrorComponent { constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .pipe(catchError(error => { console.error('Error occurred:', error); return of([]); })) .subscribe(response => { console.log(response); }); } }
The `@Directive` decorator is used to create custom directives that can manipulate the DOM.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
The `Renderer2` service allows you to interact with the DOM in a safe way.
import { Directive, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[appColor]'
})
export class ColorDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
}
}
The `@ViewChildren` decorator allows you to query and access multiple child elements or components.
import { Component, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-children', template: `
{{ i }}
`, }) export class ViewChildrenComponent implements AfterViewInit { @ViewChildren('item') items: QueryList
; ngAfterViewInit() { this.items.forEach(item => { console.log(item.nativeElement.textContent); }); } }
Feature modules are created using the `@NgModule` decorator to group related components, directives, and services.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [CommonModule],
declarations: [FeatureComponent],
exports: [FeatureComponent]
})
export class FeatureModule { }
The `RouterModule` is used to configure routes and navigation in an Angular application.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The `ActivatedRoute` service allows you to access route parameters in your component.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-params', template: `
Route ID: {{ id }}
`, }) export class RouteParamsComponent implements OnInit { id: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id'); }); } }
The `HttpClient` service can send POST requests with JSON data using the `post` method.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-post-request', template: `
Check console for response
`, }) export class PostRequestComponent { constructor(private http: HttpClient) { this.http.post('https://api.example.com/data', { key: 'value' }) .subscribe(response => { console.log(response); }); } }
The `FormArray` class allows you to manage an array of form controls in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`,
})
export class FormArrayComponent {
form: FormGroup;
get items() {
return this.form.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array(['', '', ''])
});
}
}
The `HttpParams` class is used to construct query parameters for an HTTP request.
import { Component } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-http-params', template: `
Check console for response
`, }) export class HttpParamsComponent { constructor(private http: HttpClient) { const params = new HttpParams().set('param1', 'value1').set('param2', 'value2'); this.http.get('https://api.example.com/data', { params }) .subscribe(response => { console.log(response); }); } }
The `@HostBinding` decorator allows you to bind properties of the host element in a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}
The `@HostListener` decorator allows you to listen to events on the host element in a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
The `@Inject` decorator is used to specify a dependency to be injected into a service or component.
import { Injectable, Inject } from '@angular/core';
import { MyService } from './my-service.service';
@Injectable({
providedIn: 'root'
})
export class MyComponentService {
constructor(@Inject(MyService) private myService: MyService) {}
}
The `@Optional` decorator allows you to specify that a dependency is optional.
import { Injectable, Optional } from '@angular/core';
import { OptionalService } from './optional.service';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@Optional() private optionalService?: OptionalService) {}
}
The `@Self` decorator ensures that a dependency is resolved from the same injector, not from parent injectors.
import { Injectable, Self } from '@angular/core';
import { MyService } from './my-service.service';
@Injectable({
providedIn: 'root'
})
export class AnotherService {
constructor(@Self() private myService: MyService) {}
}
The `@Attribute` decorator allows you to access the value of an attribute on the host element.
import { Directive, Attribute } from '@angular/core';
@Directive({
selector: '[appAttribute]'
})
export class AttributeDirective {
constructor(@Attribute('data-attribute') private dataAttribute: string) {
console.log(dataAttribute);
}
}
The `@NgModule` decorator is used to declare and import modules in an Angular application.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The `providers` array in `@NgModule` allows you to specify services to be available at the module level.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';
@NgModule({
declarations: [AppComponent],
imports: [],
providers: [MyService],
bootstrap: [AppComponent]
})
export class AppModule { }
The `@Pipe` decorator is used to create custom pipes that can transform data in templates.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
The `@Injectable` decorator is used to define a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {}
}
The `@Component` decorator is used to define a reusable component in Angular.
import { Component } from '@angular/core'; @Component({ selector: 'app-reusable', template: `
This is a reusable component
`, }) export class ReusableComponent {}
The `@ViewChild` decorator allows you to access and manipulate a child component or DOM element.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
The `@ContentChild` decorator allows you to access and manipulate content projected into a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `,
})
export class ContentComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `exports` array in `@NgModule` allows you to specify which components, directives, and pipes should be available to other modules.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';
@NgModule({
imports: [CommonModule],
declarations: [SharedComponent],
exports: [SharedComponent]
})
export class SharedModule { }
The `@Inject` decorator allows you to provide a specific token value for dependency injection.
import { Injectable, Inject, InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {
console.log(apiUrl);
}
}
The `@Directive` decorator is used to create a structural directive that can change the layout of the DOM.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appIf]'
})
export class IfDirective {
constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {}
@Input() set appIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
The `forRoot` and `forChild` methods are used to configure providers for root and feature modules, respectively.
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyService } from './my-service.service';
@NgModule({
imports: [CommonModule],
declarations: [],
exports: []
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [MyService]
};
}
}
The `BehaviorSubject` is used to manage state in Angular. It holds the current value and emits it to new subscribers.
import { BehaviorSubject } from 'rxjs';
export class StateService {
private stateSubject = new BehaviorSubject(0);
state$ = this.stateSubject.asObservable();
updateState(value: number) {
this.stateSubject.next(value);
}
}
The `OnPush` strategy improves performance by only checking for changes when the input properties change or when an event occurs.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-onpush', template: `
OnPush change detection
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OnPushComponent {}
The `@ViewEncapsulation` decorator is used to control how styles are applied to components.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-encapsulation', template: `
ViewEncapsulation example
`, styles: [`p { color: red; }`], encapsulation: ViewEncapsulation.None }) export class EncapsulationComponent {}
Route guards control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Replace with real authentication logic
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
Custom pipes can transform data based on provided arguments.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'multiply'
})
export class MultiplyPipe implements PipeTransform {
transform(value: number, multiplier: number): number {
return value * multiplier;
}
}
The `FormBuilder` service can be used to create complex forms with nested form groups.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-nested-form',
template: `
`,
})
export class NestedFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
personalInfo: this.fb.group({
name: [''],
age: ['']
}),
address: this.fb.group({
street: [''],
city: ['']
})
});
}
}
Lazy-loaded modules can be configured in the `@NgModule` using the `loadChildren` property in routes.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Providing a service in the `@NgModule` ensures that it is a singleton across the entire application.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';
@NgModule({
declarations: [AppComponent],
imports: [],
providers: [MyService], // Singleton service
bootstrap: [AppComponent]
})
export class AppModule { }
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
headers: req.headers.set('Authorization', 'Bearer token')
});
return next.handle(clonedRequest);
}
}
The `ChangeDetectorRef` service allows you to manually trigger change detection in your components.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detect', template: `
Manual change detection
`, }) export class ManualDetectComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
The `Renderer2` service provides methods to manipulate the DOM in a platform-independent way.
import { Directive, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private renderer: Renderer2, private el: ElementRef) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
}
The `NgFor` directive is used to loop through an array of objects in the template.
import { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
template: `
{{ item.name }}
`,
})
export class ItemListComponent {
items = [{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }];
}
The `NgIf` directive allows you to conditionally include or exclude elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
This element is conditionally rendered
`, }) export class ConditionalComponent { isVisible = true; }
The `FormArray` allows you to manage a dynamic list of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
The `@HostListener` decorator allows you to listen to DOM events directly in your component.
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-host-listener', template: `
HostListener example
`, }) export class HostListenerComponent { @HostListener('click', ['$event']) onClick(event: Event) { console.log('Element clicked!', event); } }
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
ngOnChanges example
`, }) export class ChangesComponent implements OnChanges { @Input() data: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes detected:', changes); } }
The `ngOnInit` lifecycle hook is used to perform initialization tasks for the component.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
ngOnInit example
`, }) export class InitComponent implements OnInit { data: string; ngOnInit() { this.data = 'Initialized data'; } }
The `ngOnDestroy` lifecycle hook is used to perform cleanup tasks before the component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
ngOnDestroy example
`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
The `@Input` decorator allows a child component to receive data from a parent, while `@Output` allows the child to emit events to the parent.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ` `, }) export class ChildComponent { @Input() message: string; @Output() messageEvent = new EventEmitter
(); sendMessage() { this.messageEvent.emit('Message from child'); } } @Component({ selector: 'app-parent', template: `
Received Message: {{ receivedMessage }}
`, }) export class ParentComponent { parentMessage = 'Message from parent'; receivedMessage: string; receiveMessage(message: string) { this.receivedMessage = message; } }
The `ngSwitch` directive allows you to conditionally display elements based on a value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Value is A
Value is B
Default value
`, }) export class SwitchComponent { value = 'A'; }
The `@Injectable` decorator is used to mark a class as a service that can be injected. You can specify the provider in `@NgModule` or directly in the component.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Singleton service provided at the root level
})
export class MyService {}
The `@ContentChild` decorator is used to access a child component or directive that is projected into a content slot.
import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent implements AfterContentInit {
@ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
console.log(this.child);
}
}
The `@ViewChild` decorator is used to access a child component or directive within the view.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
The `ngModel` directive is used for two-way data binding with form controls.
import { Component } from '@angular/core'; @Component({ selector: 'app-model', template: `
{{ value }}
` }) export class ModelComponent { value: string = ''; }
The `AsyncPipe` subscribes to an observable or promise and returns the latest value it has emitted.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `
{{ data$ | async }}
` }) export class AsyncComponent { data$: Observable
= of('Hello World'); }
The `ngClass` directive allows you to dynamically add or remove CSS classes based on component state.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Dynamic Class
` }) export class ClassComponent { isActive = true; }
The `ngStyle` directive allows you to dynamically set inline styles on an element.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `
Styled Text
` }) export class StyleComponent { color = 'blue'; fontSize = '20px'; }
The `trackBy` function helps Angular optimize rendering by tracking items in a list.
import { Component } from '@angular/core';
@Component({
selector: 'app-trackby',
template: `
{{ item.name }}
`
})
export class TrackByComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
The `ngIf` directive can be used with `else` to display alternate content based on a condition.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-else', template: `
Visible Content
Not Visible Content ` }) export class IfElseComponent { isVisible = true; }
The `@HostBinding` decorator allows you to bind properties to the host element of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlight') isHighlighted = true;
}
The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked!', event);
}
}
The `HttpClient` service is used to make HTTP requests and handle responses.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { Observable } from 'rxjs'; @Component({ selector: 'app-http', template: `
Data: {{ data$ | async }}
` }) export class HttpComponent { data$: Observable
; constructor(private http: HttpClient) { this.data$ = this.http.get('https://api.example.com/data'); } }
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
setHeaders: { Authorization: 'Bearer token' }
});
return next.handle(clonedRequest);
}
}
The `Router` service is used to navigate between routes programmatically.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: ``
})
export class NavigateComponent {
constructor(private router: Router) {}
goToPage() {
this.router.navigate(['/page']);
}
}
The `ActivatedRoute` service allows you to access route parameters and query parameters.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route', template: `
Param: {{ param }}
` }) export class RouteComponent implements OnInit { param: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe(params => { this.param = params['id']; }); } }
Route guards are used to protect routes based on certain conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Check authentication
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
The `RouterOutlet` directive is used to display routed components based on the active route.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
const routes: Routes = [
{ path: '', component: HomeComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
@Component({
selector: 'app-root',
template: ` `
})
export class AppComponent {}
Dependency Injection is used to inject services into components or other services.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService {} import { Component } from '@angular/core'; import { MyService } from './my.service'; @Component({ selector: 'app-example', template: `
Service injected
` }) export class ExampleComponent { constructor(private myService: MyService) {} }
Custom pipes are used to transform data before displaying it in the template.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'reverse' }) export class ReversePipe implements PipeTransform { transform(value: string): string { return value.split('').reverse().join(''); } } @Component({ selector: 'app-pipe', template: `
{{ 'Angular' | reverse }}
` }) export class PipeComponent {}
The `ChangeDetectionStrategy` is used to control how Angular checks for changes in a component.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-detection', template: `
Change Detection Strategy
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class DetectionComponent {}
The `@Inject` decorator is used to specify a provider to inject into a constructor when the dependency is not directly injectable.
import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class DocumentService {
constructor(@Inject(DOCUMENT) private document: Document) {}
}
The `@Component` decorator is used to define metadata for a component, such as its selector, template, and styles.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {}
The `@NgModule` decorator defines an Angular module by providing metadata, such as declarations, imports, and providers.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
The `ReactiveFormsModule` provides reactive form capabilities in Angular, allowing you to build and manage forms programmatically.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
submit() {
console.log(this.form.value);
}
}
The `FormsModule` provides support for template-driven forms in Angular, allowing you to build forms declaratively.
import { Component } from '@angular/core';
@Component({
selector: 'app-template-form',
template: `
`
})
export class TemplateFormComponent {
submit(form: any) {
console.log(form.value);
}
}
Interceptors can be used with `HttpClient` to log HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
console.log('Request made:', req);
return next.handle(req);
}
}
The `@Output` decorator allows a child component to emit events to a parent component.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit();
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
onNotify() {
console.log('Notification received!');
}
}
The `ng-template` directive allows you to define reusable templates that can be used with structural directives.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
Hello, {{ name }}!
` }) export class TemplateComponent {}
The `ng-content` directive is used to project content from a parent component into a child component.
import { Component } from '@angular/core'; @Component({ selector: 'app-child', template: `
` }) export class ChildComponent {} import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `
Projected Content
` }) export class ParentComponent {}
The `ComponentFactoryResolver` allows you to dynamically create components at runtime.
import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-dynamic-loader',
template: ` `
})
export class DynamicLoaderComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
loadComponent() {
const factory = this.resolver.resolveComponentFactory(DynamicComponent);
this.container.createComponent(factory);
}
}
The `FormArray` is used to manage a collection of form controls, which can be dynamically added or removed.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
The `ChangeDetectorRef` service is used to manually trigger change detection in Angular.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detection', template: `
Manual Change Detection
` }) export class ManualDetectionComponent { constructor(private cdr: ChangeDetectorRef) {} detectChanges() { this.cdr.detectChanges(); } }
The `@HostListener` decorator allows you to listen to DOM events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Element clicked!', event);
}
}
The `@ViewChild` decorator allows you to access child components, directives, or DOM elements from the parent component.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
@ViewChild('child') child: ElementRef;
clickChild() {
console.log(this.child);
}
}
The `@ContentChild` decorator allows you to access content projected into a component using `ng-content`.
import { Component, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `
})
export class ContentComponent {
@ContentChild('projectedContent') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `NgZone` service allows you to run code inside or outside Angular's zone, which affects change detection.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
NgZone Example
` }) export class ZoneComponent { constructor(private ngZone: NgZone) {} runOutsideAngular() { this.ngZone.runOutsideAngular(() => { console.log('Running outside Angular zone'); }); } }
The `ViewEncapsulation` enum controls how styles are applied to components.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-encapsulation', template: `
View Encapsulation Example
`, styles: [`p { color: blue; }`], encapsulation: ViewEncapsulation.Emulated }) export class EncapsulationComponent {}
Lazy-loaded modules are configured using `NgModule` and the `RouterModule.forRoot` method with the `loadChildren` property.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The `ChangeDetectionStrategy.OnPush` strategy optimizes performance by checking for changes only when input properties change or events occur.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-performance', template: `
OnPush Change Detection
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class PerformanceComponent {}
The `ng-container` directive allows you to conditionally render elements without adding extra DOM nodes.
import { Component } from '@angular/core'; @Component({ selector: 'app-container', template: `
Conditionally Rendered Content
` }) export class ContainerComponent { isVisible = true; }
The `@Injectable` decorator marks a class as a service that can be injected into other classes.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Data 1', 'Data 2', 'Data 3'];
}
}
The `ngIf` directive conditionally includes a template based on the value of an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-condition', template: `
This content is visible
` }) export class ConditionComponent { isVisible = true; }
The `ngFor` directive is used to iterate over a list of items and render them in the template.
import { Component } from '@angular/core';
@Component({
selector: 'app-list',
template: `
{{ item }}
`
})
export class ListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngSwitch` directive allows you to display different templates based on a value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red color
Blue color
Default color
` }) export class SwitchComponent { color = 'blue'; }
The `@ViewChild` decorator is used to get a reference to a child component or element in the template.
import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Child Paragraph
` }) export class ViewChildComponent { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
The `ngStyle` directive allows you to apply dynamic styles to an element based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `
Styled Text
` }) export class StyleComponent { color = 'red'; fontSize = 20; }
The `ngClass` directive allows you to conditionally apply one or more CSS classes to an element.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Conditional Classes
` }) export class ClassComponent { isActive = true; isDisabled = false; }
The `@Input` decorator allows a child component to receive data from its parent component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
Received: {{ data }}
` }) export class ChildComponent { @Input() data: string; } import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `
` }) export class ParentComponent { parentData = 'Data from parent'; }
The `@HostBinding` decorator allows you to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}
The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Element clicked:', event);
}
}
The `Router` service is used to navigate between different routes in an Angular application.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``
})
export class NavigationComponent {
constructor(private router: Router) {}
navigate() {
this.router.navigate(['/details']);
}
}
The `ActivatedRoute` service is used to access route parameters and other information about the current route.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-details', template: `
Item ID: {{ itemId }}
` }) export class DetailsComponent implements OnInit { itemId: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.itemId = this.route.snapshot.paramMap.get('id'); } }
The `RouterModule` is used to configure application routes using the `RouterModule.forRoot` method.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The `CanActivate` guard is used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Example condition
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
The `HttpClient` service is used to make HTTP requests and handle responses.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data');
}
}
The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({ setHeaders: { Authorization: 'Bearer token' } });
return next.handle(authReq);
}
}
The `FormBuilder` service simplifies the creation of reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: [''],
email: ['']
});
}
}
The `FormArray` allows you to manage a collection of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
The `ngOnChanges` lifecycle hook responds to changes in input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
Previous: {{ prevValue }}, Current: {{ currentValue }}
` }) export class ChangesComponent implements OnChanges { @Input() value: string; prevValue: string; currentValue: string; ngOnChanges(changes: SimpleChanges) { if (changes.value) { this.prevValue = changes.value.previousValue; this.currentValue = changes.value.currentValue; } } }
The `ngAfterViewInit` lifecycle hook is used to perform actions after the view and child views have been initialized.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-after-view', template: `
View Initialized
` }) export class AfterViewComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
The `ng-content` directive allows you to project content into a component's view.
import { Component } from '@angular/core'; @Component({ selector: 'app-card', template: `
` }) export class CardComponent {}
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `
Card Title
Card content goes here.
` }) export class AppComponent {}
The `ng-template` directive defines reusable templates that can be instantiated later.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
This is a reusable template.
` }) export class TemplateComponent {}
The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection performance.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-optimized', template: `
Optimized Change Detection
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OptimizedComponent {}
The `Renderer2` service is used to safely manipulate DOM elements without direct access.
import { Component, ElementRef, Renderer2 } from '@angular/core'; @Component({ selector: 'app-renderer', template: `
Text
` }) export class RendererComponent { constructor(private renderer: Renderer2, private el: ElementRef) {} ngAfterViewInit() { const paragraph = this.el.nativeElement.querySelector('p'); this.renderer.setStyle(paragraph, 'color', 'blue'); } }
The `@Directive` decorator is used to create custom directives that can modify the behavior of elements.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
The `@NgModule` decorator defines a module and its components, directives, and services.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FeatureComponent } from './feature/feature.component';
@NgModule({
declarations: [
AppComponent,
FeatureComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Dependency Injection allows you to provide and inject services into components or other services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
login() {
console.log('User logged in');
}
}
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
template: ``
})
export class LoginComponent {
constructor(private authService: AuthService) {}
login() {
this.authService.login();
}
}
The `Observable` class is used to handle asynchronous data streams and is often used with Angular's `HttpClient`.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Component({ selector: 'app-data', template: `
{{ data | json }}
` }) export class DataComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.getData().subscribe(response => this.data = response); } getData(): Observable
{ return this.http.get('https://api.example.com/data'); } }
RxJS operators are used to transform and manipulate data streams.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-transformed-data', template: `
{{ data | json }}
` }) export class TransformedDataComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.getData().pipe( map(response => response.items) ).subscribe(items => this.data = items); } getData() { return this.http.get
('https://api.example.com/data'); } }
The `@Output` decorator and `EventEmitter` are used to emit events from a child component to its parent.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit('Event from child');
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
handleNotification(message: string) {
console.log(message);
}
}
The `@HostBinding` decorator allows you to bind properties of the host element.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor: string = 'yellow';
}
The `@HostListener` decorator listens to events on the host element.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('Element clicked:', event);
}
}
The `ngFor` directive is used to loop through a collection and render each item.
import { Component } from '@angular/core';
@Component({
selector: 'app-list',
template: `
{{ item }}
`
})
export class ListComponent {
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngIf` directive is used to conditionally include or exclude elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
This text is visible
` }) export class ConditionalComponent { isVisible = true; }
The `ngSwitch` directive allows you to conditionally display elements based on a switch value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red color
Green color
Default color
` }) export class SwitchComponent { color = 'green'; }
The `ngStyle` directive allows you to dynamically set CSS styles based on an object.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `
Styled Div
` }) export class StyleComponent { styles = { 'color': 'blue', 'font-size': '20px' }; }
The `ngClass` directive allows you to conditionally apply CSS classes based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Styled Div
` }) export class ClassComponent { isActive = true; }
The `ngModel` directive is used for two-way data binding between form inputs and component properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
Hello, {{ name }}!
` }) export class TwoWayBindingComponent { name: string = ''; }
The `FormControl` class is used to manage the state and validation of individual form controls.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form-control', template: `
Control Value: {{ nameControl.value }}
` }) export class FormControlComponent { nameControl = new FormControl(''); }
The `FormGroup` class is used to group related `FormControl` instances into a single entity.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form-group',
template: `
`
})
export class FormGroupComponent {
form = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
}
The `@ViewChild` decorator allows you to access child components or DOM elements from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-child', template: `
Child Component
` }) export class ChildComponent {} @Component({ selector: 'app-parent', template: `
` }) export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent) child!: ChildComponent; @ViewChild('childParagraph') childParagraph!: ElementRef; ngAfterViewInit() { console.log(this.child); console.log(this.childParagraph.nativeElement.textContent); } logChildParagraph() { console.log(this.childParagraph.nativeElement.textContent); } }
The `@ContentChild` decorator allows you to access content projected into the component using `ng-content`.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-card', template: `
` }) export class CardComponent implements AfterContentInit { @ContentChild('cardContent') cardContent!: ElementRef; ngAfterContentInit() { console.log(this.cardContent.nativeElement.textContent); } } @Component({ selector: 'app-root', template: `
Card Content
` }) export class AppComponent {}
The `@Input` decorator allows a parent component to pass data to a child component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
Received: {{ data }}
` }) export class ChildComponent { @Input() data!: string; } @Component({ selector: 'app-parent', template: `
` }) export class ParentComponent { parentData = 'Data from Parent'; }
The `@Output` decorator is used to create custom events that a child component can emit to its parent.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() message = new EventEmitter();
sendMessage() {
this.message.emit('Hello from Child');
}
}
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
receiveMessage(message: string) {
console.log(message);
}
}
The `ReactiveForms` module provides a way to create forms with validation using `FormGroup` and `FormControl`.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form = new FormGroup({
name: new FormControl('', Validators.required)
});
onSubmit() {
console.log(this.form.value);
}
}
The `ngFor` directive can be used with a custom template to display a list of items.
import { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
template: `
{{ i + 1 }}. {{ item }}
`
})
export class ItemListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngIf` directive can be used with the `else` clause to conditionally display alternate content.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
Content is visible
Content is hidden
` }) export class ConditionalComponent { isVisible = true; }
The `ngSwitch` directive can be used with multiple `ngSwitchCase` directives to handle different cases.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red
Green
Blue
Unknown color
` }) export class SwitchComponent { color = 'green'; }
The `ngStyle` directive allows you to conditionally apply styles based on an object.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `
Conditional Style
` }) export class StyleComponent { isActive = true; }
The `ngClass` directive allows you to toggle multiple CSS classes based on an object or array.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Styled Div
` }) export class ClassComponent { isActive = true; isHighlighted = false; }
The `ngModel` directive is used for two-way data binding in forms.
import { Component } from '@angular/core';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
name = '';
}
The `FormBuilder` service helps in creating `FormGroup` and `FormControl` instances more easily.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `FormArray` class is used to handle an array of form controls or groups.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([''])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
The `AsyncPipe` subscribes to an observable or promise and returns the latest value.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `
{{ data }}
` }) export class AsyncComponent { data$: Observable
= of('Asynchronous Data'); }
The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection by checking only when input properties change.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-on-push', template: `
OnPush Change Detection
`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OnPushComponent {}
The `@Injectable` decorator is used to mark a class as available to be injected. Services can be provided at different levels, such as in the root or in a specific module.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // or provide in a specific module
})
export class DataService {
constructor() { }
}
The `HttpClient` service is used to make HTTP requests and handle responses.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-http', template: `
{{ data | json }}
` }) export class HttpComponent { data: any; constructor(private http: HttpClient) { } fetchData() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
The `Router` service is used to navigate between routes programmatically.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``
})
export class NavigationComponent {
constructor(private router: Router) { }
goToHome() {
this.router.navigate(['/home']);
}
}
The `ActivatedRoute` service is used to access route parameters and query parameters.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-params', template: `
Route Parameter: {{ id }}
` }) export class RouteParamsComponent implements OnInit { id!: string; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id')!; }); } }
The `RouterModule` is used to define and configure routes in an Angular application.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
An Angular pipe is used to transform data in templates. You create a pipe by using the `@Pipe` decorator.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
Custom validators can be created by implementing the `Validator` interface or by creating a function that returns a validator function.
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { 'forbiddenName': { value: control.value } } : null;
};
}
`@HostBinding` binds a property of the host element, while `@HostListener` listens to events on the host element.
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'transparent';
@HostListener('mouseenter') onMouseEnter() {
this.backgroundColor = 'yellow';
}
@HostListener('mouseleave') onMouseLeave() {
this.backgroundColor = 'transparent';
}
}
`ChangeDetectorRef` is used to manually trigger change detection or detach the change detector.
import { ChangeDetectorRef, Component } from '@angular/core'; @Component({ selector: 'app-manual-change-detection', template: `
{{ data }}
` }) export class ManualChangeDetectionComponent { data = 'Initial Data'; constructor(private cdr: ChangeDetectorRef) {} updateData() { this.data = 'Updated Data'; this.cdr.detectChanges(); // Manually trigger change detection } }
The `ngOnDestroy` lifecycle hook is used to clean up resources before the component is destroyed.
import { Component, OnDestroy } from '@angular/core'; @Component({ selector: 'app-cleanup', template: `
Cleanup Component
` }) export class CleanupComponent implements OnDestroy { ngOnDestroy() { console.log('CleanupComponent destroyed'); // Perform cleanup here } }
`@ViewChild` allows you to access a child component or DOM element in the parent component class.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
@ViewChild('child') childComponent!: ElementRef;
ngAfterViewInit() {
console.log(this.childComponent.nativeElement);
}
}
`@ContentChild` allows you to access projected content within a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `
})
export class ContentComponent implements AfterContentInit {
@ContentChild('content') content!: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `ngOnChanges` lifecycle hook is used to detect changes to input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
Changes Component
` }) export class ChangesComponent implements OnChanges { @Input() data!: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes detected:', changes); } }
The `ngSwitch` directive is used to conditionally display content based on a switch expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Case A
Case B
Default Case
` }) export class SwitchComponent { condition = 'A'; }
The `ngClass` directive allows you to apply multiple CSS classes dynamically based on component data.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Conditional Classes
` }) export class ClassComponent { isActive = true; isHighlighted = false; }
The `ng-template` directive allows you to define reusable templates.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
This is a reusable template
` }) export class TemplateComponent {}
The `trackBy` function helps Angular track items in a list for better performance.
import { Component } from '@angular/core';
@Component({
selector: 'app-for',
template: `
{{ item.name }}
`
})
export class ForComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackById(index: number, item: any): number {
return item.id;
}
}
The `ngModel` directive provides two-way data binding for form elements.
import { Component } from '@angular/core'; @Component({ selector: 'app-model', template: `
Hello, {{ name }}!
` }) export class ModelComponent { name = ''; }
The `async` pipe subscribes to an Observable or Promise and returns the latest value.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `
{{ data }}
` }) export class AsyncComponent { data$: Observable
= of('Async Data'); }
The `FormBuilder` service simplifies form creation with reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
submit() {
console.log(this.form.value);
}
}
`HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
return next.handle(clonedReq);
}
}
The `Router` service allows you to navigate programmatically within your application.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: ``
})
export class NavigateComponent {
constructor(private router: Router) {}
goToHome() {
this.router.navigate(['/home']);
}
}
`ng-container` is a logical container that doesn't affect the DOM layout.
import { Component } from '@angular/core'; @Component({ selector: 'app-container', template: `
Content is visible
` }) export class ContainerComponent { isVisible = true; }
The `RouterModule` is used to configure and manage routing in Angular applications.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The `@Inject` decorator is used to specify a dependency to be injected.
import { Component, Inject } from '@angular/core'; @Component({ selector: 'app-inject', template: `
Inject Component
` }) export class InjectComponent { constructor(@Inject('API_URL') private apiUrl: string) { console.log(apiUrl); } }
`FormArray` is used to manage an array of form controls in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
form: FormGroup;
get items(): FormArray {
return this.form.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
addItem() {
this.items.push(this.fb.control(''));
}
}
The `@Optional` decorator allows you to inject dependencies that may or may not be available.
import { Component, Optional } from '@angular/core'; @Component({ selector: 'app-optional', template: `
Optional Component
` }) export class OptionalComponent { constructor(@Optional() private optionalService?: SomeService) { if (this.optionalService) { // Use the service } else { // Handle the absence of the service } } }
`NgZone` allows you to run code inside or outside Angular's change detection zone.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
Zone Component
` }) export class ZoneComponent { constructor(private ngZone: NgZone) { this.ngZone.runOutsideAngular(() => { // Code running outside Angular's zone console.log('Outside Angular Zone'); // Simulate an async operation setTimeout(() => { this.ngZone.run(() => { console.log('Back inside Angular Zone'); }); }, 1000); }); } }
The `@Injectable` decorator with `providedIn` allows you to specify the provider scope for a service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Service is available throughout the app
})
export class MyService {
constructor() {}
}
`@ContentChildren` is used to access multiple projected content elements.
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: `
`
})
export class ContentComponent implements AfterContentInit {
@ContentChildren('content') contents!: QueryList;
ngAfterContentInit() {
this.contents.forEach(content => {
console.log(content.nativeElement.textContent);
});
}
}
The `@Host` decorator allows you to inject a dependency from the host element.
import { Component, Host } from '@angular/core'; @Component({ selector: 'app-host', template: `
Host Component
` }) export class HostComponent { constructor(@Host() private parentComponent: ParentComponent) { console.log(this.parentComponent); } }
`@Input` and `@Output` are used to pass data between parent and child components.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}
` }) export class ChildComponent { @Input() data!: string; @Output() dataChange = new EventEmitter
(); sendData() { this.dataChange.emit('New Data'); } } @Component({ selector: 'app-parent', template: ` ` }) export class ParentComponent { parentData = 'Initial Data'; handleDataChange(newData: string) { this.parentData = newData; } }
The `@Inject` decorator is used to inject tokens for dependency injection.
import { InjectionToken, Injectable, Inject } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {
console.log(apiUrl);
}
}
`ngIf` with `else` allows you to handle conditional templates more elegantly.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-else', template: `
Visible
Not Visible
` }) export class IfElseComponent { isVisible = true; }
`ngFor` with `index` allows you to display the index of items in a list.
import { Component } from '@angular/core';
@Component({
selector: 'app-for-index',
template: `
{{ i + 1 }}. {{ item }}
`
})
export class ForIndexComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
`@ViewChild` allows you to access a child component or element in the template.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Content
` }) export class ViewChildComponent implements AfterViewInit { @ViewChild('content') content!: ElementRef; ngAfterViewInit() { console.log(this.content.nativeElement.textContent); } }
`ngClass` is used to conditionally apply CSS classes based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `
Conditional Classes
` }) export class ClassComponent { isActive = true; }
`ngStyle` allows you to apply inline styles dynamically based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `
Dynamic Styles
` }) export class StyleComponent { color = 'blue'; fontSize = 16; }
The `@HostListener` decorator allows you to listen to DOM events on the host element.
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-host-listener', template: `
Host Listener Component
` }) export class HostListenerComponent { @HostListener('click', ['$event']) onClick(event: Event) { console.log('Element clicked', event); } }
`ChangeDetectorRef` allows you to manually trigger change detection in Angular.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-change-detector', template: `
Change Detector Component
` }) export class ChangeDetectorComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
The `@Directive` decorator is used to create custom directives.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
The `@Pipe` decorator is used to create custom pipes.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
The `@NgModule` decorator is used to define the metadata for an Angular module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
Nested routes can be defined using child routes in the Angular Router configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
const routes: Routes = [
{ path: 'parent', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
The `@NgModule` decorator allows you to import and export modules within your application.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, FormsModule],
exports: [CommonModule, FormsModule]
})
export class SharedModule {}
`ngSwitch` allows you to conditionally display content based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red
Green
Default
` }) export class SwitchComponent { color = 'green'; }
`ngIf` with `then` allows you to specify a template to display when the condition is true.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-then', template: `
Visible
Not Visible
` }) export class IfThenComponent { isVisible = true; }
`ngFor` can be used to iterate over objects and access their properties.
import { Component } from '@angular/core';
@Component({
selector: 'app-for-object',
template: `
{{ key }}: {{ myObject[key] }}
`
})
export class ForObjectComponent {
myObject = { name: 'Alice', age: 30, city: 'New York' };
objectKeys(obj: any) {
return Object.keys(obj);
}
}
`@Injectable` can be used with custom providers to configure service injection.
import { Injectable, InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}
}
`@ViewChild` with `static: true` allows access to child components before the view initialization.
import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-static-view-child', template: `
Static View Child Content
` }) export class StaticViewChildComponent implements AfterViewInit { @ViewChild('content', { static: true }) content!: ElementRef; ngAfterViewInit() { console.log(this.content.nativeElement.textContent); } }
`@Output` with `EventEmitter` allows you to emit custom events from a child component.
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-output', template: ` ` }) export class OutputComponent { @Output() notify = new EventEmitter
(); notifyParent() { this.notify.emit('Hello from child!'); } } @Component({ selector: 'app-parent', template: `
{{ message }}
` }) export class ParentComponent { message = ''; handleNotification(msg: string) { this.message = msg; } }
Lazy loading is implemented using the `loadChildren` property in the route configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
`NgZone` allows you to manage Angular's change detection manually.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
Zone Component
` }) export class ZoneComponent { constructor(private ngZone: NgZone) {} runOutsideAngular() { this.ngZone.runOutsideAngular(() => { // Code running outside Angular's zone console.log('Running outside Angular zone'); setTimeout(() => { this.ngZone.run(() => { console.log('Running inside Angular zone'); }); }, 1000); }); } }
`ChangeDetectorRef` is used to manually trigger change detection.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-change-detector', template: `
Change Detector Component
` }) export class ChangeDetectorComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
`@HostBinding` allows you to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHostBinding]'
})
export class HostBindingDirective {
@HostBinding('class.active') isActive = true;
}
`@HostListener` is used to listen to events on the host element.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListener]'
})
export class HostListenerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked', event);
}
}
`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}
` }) export class ChildComponent { @Input() data!: string; @Output() notify = new EventEmitter
(); notifyParent() { this.notify.emit(); } } @Component({ selector: 'app-parent', template: `
{{ message }}
` }) export class ParentComponent { parentData = 'Data from parent'; message = ''; handleNotification() { this.message = 'Child component notified!'; } }
The `Router` allows you to handle route parameters using route configuration and activated route service.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-param', template: `
Route Param: {{ id }}
` }) export class RouteParamComponent implements OnInit { id!: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id') || ''; }); } } import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { RouteParamComponent } from './route-param.component'; const routes: Routes = [ { path: 'param/:id', component: RouteParamComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
Route guards are used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isLoggedIn = false; // Replace with real authentication check
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { HomeComponent } from './home.component';
import { LoginComponent } from './login.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Module dependencies are defined using the `imports` array in the `@NgModule` decorator.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [SomeComponent],
exports: [SomeComponent]
})
export class SomeModule {}
The `@Component` decorator is used to configure metadata such as selector, template, and styles.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: `
Example Component
`, styles: [`p { color: blue; }`] }) export class ExampleComponent {}
A feature module is created using `@NgModule` to group related components, directives, and services.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [CommonModule],
declarations: [FeatureComponent],
exports: [FeatureComponent]
})
export class FeatureModule {}
`@Inject` is used to specify a custom provider for dependency injection.
import { Injectable, Inject } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}
}
Module imports and providers are defined using the `imports` and `providers` arrays in `@NgModule`.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SomeService } from './some.service';
@NgModule({
imports: [CommonModule],
providers: [SomeService]
})
export class SharedModule {}
The `@Component` decorator defines component templates and styles using `template` and `styles` properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: `
Hello World
`, styles: [`div { color: red; }`] }) export class ExampleComponent {}
`HttpClient` is used to make HTTP GET requests and handle responses.
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-http-get', template: `
Data: {{ data | json }}
` }) export class HttpGetComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
`HttpClient` is used to make HTTP POST requests to send data to the server.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-http-post',
template: ``
})
export class HttpPostComponent {
constructor(private http: HttpClient) {}
sendData() {
const payload = { key: 'value' };
this.http.post('https://api.example.com/submit', payload).subscribe(response => {
console.log('Response:', response);
});
}
}
Query parameters can be handled using the `params` option in `HttpClient` methods.
import { HttpClient, HttpParams } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-http-params', template: `
Data: {{ data | json }}
` }) export class HttpParamsComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { let params = new HttpParams().set('param1', 'value1'); this.http.get('https://api.example.com/data', { params }).subscribe(response => { this.data = response; }); } }
`HttpInterceptor` allows you to modify HTTP requests and responses globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({
setHeaders: { Authorization: 'Bearer token' }
});
return next.handle(authReq);
}
}
Errors in HTTP requests can be handled using RxJS operators like `catchError`.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Component({ selector: 'app-http-error', template: `
Error: {{ errorMessage }}
` }) export class HttpErrorComponent { errorMessage: string = ''; constructor(private http: HttpClient) {} makeRequest() { this.http.get('https://api.example.com/data').pipe( catchError(error => { this.errorMessage = 'An error occurred!'; return of([]); }) ).subscribe(); } }
`NgForm` provides form validation and status management.
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-form-validation',
template: `
`
})
export class FormValidationComponent {
onSubmit(form: NgForm) {
if (form.valid) {
console.log('Form Submitted!', form.value);
}
}
}
`FormBuilder` is used to create reactive forms with validators.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log('Form Submitted!', this.myForm.value);
}
}
}
`FormControl` is used to manage the value and validation of individual form fields.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form-control', template: `
Name is required
` }) export class FormControlComponent { nameControl = new FormControl('', Validators.required); }
`FormArray` allows you to manage an array of form controls or groups dynamically.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
myForm: FormGroup;
get items() {
return this.myForm.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
items: this.fb.array([this.fb.control('', Validators.required)])
});
}
addItem() {
this.items.push(this.fb.control('', Validators.required));
}
onSubmit() {
if (this.myForm.valid) {
console.log('Form Submitted!', this.myForm.value);
}
}
}
`ngFor` is used to iterate over a list and render a template for each item.
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for',
template: `
{{ item }}
`
})
export class NgForComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
`ngIf` is used to conditionally include or exclude elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-if', template: `
Visible content
` }) export class NgIfComponent { isVisible = true; toggleVisibility() { this.isVisible = !this.isVisible; } }
`ngSwitch` is used to conditionally include or exclude elements based on a switch expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-switch', template: `
Option 1 content
Option 2 content
Default content
` }) export class NgSwitchComponent { selectedOption = 'option1'; selectOption(option: string) { this.selectedOption = option; } }
`ngClass` allows you to conditionally apply CSS classes to elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-class', template: `
Content
`, styles: [` .active { color: green; } .inactive { color: red; } `] }) export class NgClassComponent { isActive = true; toggleStatus() { this.isActive = !this.isActive; } }
`ngStyle` allows you to conditionally apply inline styles to elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-style', template: `
Styled Content
` }) export class NgStyleComponent { isActive = true; toggleStatus() { this.isActive = !this.isActive; } }
`ng-container` is used to group elements and apply structural directives without adding extra DOM nodes.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-container', template: `
Visible Content 1
Visible Content 2
` }) export class NgContainerComponent { isVisible = true; }
`ngModel` provides two-way data binding between the view and the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Data: {{ data }}
` }) export class NgModelComponent { data = 'Initial value'; }
`@ViewChild` allows you to access child components or DOM elements directly from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Content
` }) export class ViewChildComponent implements AfterViewInit { @ViewChild('myDiv') myDiv!: ElementRef; ngAfterViewInit() { console.log(this.myDiv.nativeElement.textContent); } changeContent() { this.myDiv.nativeElement.textContent = 'New Content'; } }
`@ContentChild` allows you to access projected content inside a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-content-child', template: `
` }) export class ContentChildComponent implements AfterContentInit { @ContentChild('projectedContent') projectedContent!: ElementRef; ngAfterContentInit() { console.log(this.projectedContent.nativeElement.textContent); } } @Component({ selector: 'app-root', template: ` Projected Content
` }) export class AppComponent {}
`@HostListener` is used to listen to DOM events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListener]'
})
export class HostListenerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked', event);
}
}
`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ` ` }) export class ChildComponent { @Input() data: string = ''; @Output() notify: EventEmitter
= new EventEmitter (); notifyParent() { this.notify.emit(); } } @Component({ selector: 'app-parent', template: `
Received Data: {{ receivedData }}
` }) export class ParentComponent { parentData = 'Data from parent'; receivedData = ''; handleNotification() { this.receivedData = 'Notification received from child!'; } }