Angular is a TypeScript-based open-source web application framework developed by Google. It is used for building single-page applications (SPAs) with a component-based architecture.
A component is a fundamental building block of Angular applications. It consists of an HTML template, a CSS stylesheet, and a TypeScript class that defines the behavior and data of the component.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: 'Hello, Angular!
',
styles: ['h1 { color: blue; }']
})
export class ExampleComponent {}
A service in Angular is a class that provides a specific functionality that can be shared across components. Services are used to handle data operations and business logic.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Service Data';
}
}
Angular CLI (Command Line Interface) is a tool used to automate the workflow of Angular applications. It helps with creating new projects, generating components, and running development servers.
To create a new Angular component using Angular CLI, you can run the command:
ng generate component component-name
or
ng g c component-name
Data binding is the mechanism to synchronize data between the model and the view. Angular supports several types of data binding: interpolation, property binding, event binding, and two-way data binding.
Hello, {{ name }}!
Directives are classes that add behavior to elements in your Angular applications. They are used to manipulate the DOM or add new behavior to elements.
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
Angular Router is used for navigating between different views or pages in a single-page application. It allows for routing configurations and route parameters.
Routes are defined in the `RouterModule` configuration. Each route maps a path to a component.
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 {}
Angular modules are classes that group related components, services, directives, and pipes. They help to organize and manage the application structure.
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 {}
Dependency injection is a design pattern used to implement IoC (Inversion of Control). In Angular, it allows you to inject services and other dependencies into components and services.
`ngModel` is used for two-way data binding. It binds a form input element to a property in the component.
Welcome, {{ name }}!
An Angular pipe is a way to transform data in the template. Pipes are used to format or transform data before displaying it to the user.
{{ birthday | date:'longDate' }}
Angular supports template-driven and reactive forms. Template-driven forms use directives in the template, while reactive forms use FormControl and FormGroup classes.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
`ngIf` is a structural directive used to conditionally include or exclude elements from the DOM based on a boolean expression.
Content to show when isVisible is true
You can pass data from a parent component to a child component using @Input properties.
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 = 'Hello from parent!';
}
`ngFor` is a structural directive used to iterate over a list or array and render a template for each item.
- {{ item }}
`AppModule` is the root module of an Angular application. It is responsible for bootstrapping the application and declaring the components, directives, and services that belong to the module.
Routes are defined using the `RouterModule` with an array of route configurations that map URL paths to components.
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 {}
Lifecycle hooks are methods that allow you to tap into key moments in the lifecycle of a component or directive, such as initialization and destruction.
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: 'Example component
'
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
`ngClass` is used to dynamically add or remove CSS classes to elements based on the evaluation of expressions.
Content
`ngSwitch` is used to conditionally display one of many elements based on the value of an expression.
Red
Blue
Default
`ngForTrackBy` helps Angular track which items have changed, are added, or are removed by providing a unique identifier for each item in the list.
{{ item.name }}
trackById(index: number, item: any): number { return item.id; }
`ngIf` can be used with `else` to provide an alternative template when the condition is false.
Content to show when isVisible is true
Content to show when isVisible is false
`FormBuilder` is a service used to create and manage reactive forms in Angular. It simplifies the creation of `FormGroup` and `FormControl` instances.
import { FormBuilder, FormGroup } from '@angular/forms';
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: [''],
email: ['']
});
}
The `@Injectable` decorator is used to mark a class as available for dependency injection. It tells Angular that the class can be injected into other classes as a dependency.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {}
`@Input` is used to pass data from a parent component to a child component, while `@Output` is used to emit events from the child component to the parent.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class ChildComponent {
@Input() data: string;
@Output() event = new EventEmitter();
sendEvent() {
this.event.emit('Event data');
}
}
`AppComponent` is typically the root component of an Angular application. It serves as the main entry point for the application and bootstraps other components.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: '
Welcome to Angular!
', styles: ['h1 { color: red; }'] }) export class AppComponent {}
You can handle user input using template-driven forms or reactive forms. Template-driven forms use directives in the template, while reactive forms use form controls and groups in the component class.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `@NgModule` decorator defines an Angular module, including the components, directives, and pipes it contains, as well as other modules it depends on.
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 {}
`HttpClient` is used to make HTTP requests to a server. It provides methods such as `get`, `post`, `put`, and `delete` for handling HTTP operations.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data');
}
}
`RouterModule` is an Angular module that provides routing and navigation functionality for Angular applications. It helps to define routes and configure navigation.
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 {}
Decorators are functions that add metadata to classes, methods, or properties. Angular uses decorators to define components, directives, modules, and services.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent {}
The `@ViewChild` decorator is used to access a child component, directive, or DOM element from the parent component's class.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
template: ''
})
export class ExampleComponent {
@ViewChild('inputElement') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
A custom directive is created using the `@Directive` decorator. It can be used to add behavior to elements or components.
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', 'white');
}
}
`ChangeDetectionStrategy` determines how Angular checks for changes in the component. The two strategies are `Default` and `OnPush`.
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
', changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleComponent {}
`ngModel` is used for two-way data binding between the model and the view. It binds a form control to a property in the component class.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: '
Hello {{ name }}
' }) export class ExampleComponent { name: string = ''; }
The `@HostBinding` decorator binds a property or attribute of the host element of a directive or component 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;
}
`ng-content` is used to project content into a component from its parent component. It allows you to create reusable components with customizable content.
@Component({
selector: 'app-card',
template: ' '
})
export class CardComponent {}
You can use the `Router` service to navigate to different routes programmatically by calling its `navigate` method.
import { Router } from '@angular/router';
constructor(private router: Router) {}
navigateToHome() {
this.router.navigate(['/home']);
}
The `ngOnInit` lifecycle hook is called after the component's data-bound properties have been initialized. It is commonly used for initialization logic.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
An Angular service is defined using the `@Injectable` decorator. It is a class that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['data1', 'data2'];
}
}
The `@Directive` decorator is used to create custom directives in Angular. Directives can change the appearance or behavior of elements in 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.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
An Angular module is created using the `@NgModule` decorator. It defines a module that groups components, directives, pipes, and services.
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 {}
`ngIf` is a structural directive that conditionally includes or removes an element from the DOM based on the truthiness of an expression.
This is visible
`ngFor` is a structural directive used to repeat a block of HTML for each item in a list.
{{ item }}
The `@Component` decorator is used to define a component in Angular. It specifies the selector, template, and styles for the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
', styles: ['p { color: blue; }'] }) export class ExampleComponent {}
Dependency injection in Angular is implemented by providing services in the component's or module's `providers` array and injecting them into the constructor of the class.
import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent { constructor(private dataService: DataService) {} }
The `@Pipe` decorator is used to define custom pipes in Angular, which transform data in templates.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
The `ngOnChanges` lifecycle hook is called when an input property of the component changes. It is used to perform actions based on the input property changes.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent implements OnChanges { @Input() data: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes detected:', changes); } }
`ngModel` is a directive used for two-way data binding between the form controls and component properties.
Hello {{ name }}
Reactive forms are created using `FormGroup` and `FormControl` classes from `@angular/forms`.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
The `@HostListener` decorator is used to listen to events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appEvent]'
})
export class EventDirective {
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('Element clicked:', event);
}
}
The `@Input` decorator is used to pass data 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; }
The `@Output` decorator is used to emit events from a child component to a parent component.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class ChildComponent {
@Output() dataSent = new EventEmitter();
sendData() {
this.dataSent.emit('Some data');
}
}
HTTP requests in Angular are handled using the `HttpClient` service from `@angular/common/http`.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-http', template: '
HTTP request component
' }) export class HttpComponent { constructor(private http: HttpClient) {} getData() { this.http.get('https://api.example.com/data').subscribe(response => { console.log(response); }); } }
The `RouterModule` is used to configure routes in an Angular application, allowing navigation between different views or components.
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 `@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 UserService {
getUser() {
return { name: 'John Doe' };
}
}
The `imports` property in `@NgModule` is used to import other Angular modules into the current module, making their components, directives, and pipes available for use.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [MyComponent]
})
export class MyModule {}
The `@HostBinding` decorator is used to bind a property or attribute of the host element to a property of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appColor]'
})
export class ColorDirective {
@HostBinding('style.color') color: string = 'blue';
}
The `@ViewChild` decorator is used to access a child component, directive, or DOM element within the component's template.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-example',
template: ''
})
export class ExampleComponent implements AfterViewInit {
@ViewChild('myInput') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
Angular routes with parameters are defined using a colon `:` followed by the parameter name in the route path.
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
The `ngSwitch` directive is used to conditionally include or exclude elements from the DOM based on a switch expression.
Case 1
Case 2
Default case
The `ngStyle` directive is used to apply inline styles to elements based on the values of an expression.
Styled text
The `ngContainer` is a structural directive that allows you to group elements without adding extra elements to the DOM.
Content is visible
Route guards are used to control access to routes. They implement the `CanActivate`, `CanDeactivate`, `CanLoad`, or `Resolve` interfaces.
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 {
// Implement authentication check
return true; // or false if not authenticated
}
}
The `@HostBinding` decorator is used to bind a property or attribute 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;
}
Form validation in reactive forms is done using validators such as `Validators.required`, `Validators.minLength`, etc.
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 `declarations` property in `@NgModule` is used to declare the components, directives, and pipes that belong to the module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';
@NgModule({
declarations: [MyComponent],
imports: [CommonModule],
exports: [MyComponent]
})
export class MyModule {}
The `ngModel` directive is used for two-way data binding by binding form controls to component properties.
Hello {{ name }}
The `@Injectable` decorator is used to mark a class as available to be provided and injected as a dependency in other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
getData() {
return 'Service data';
}
}
HTTP errors can be handled using the `catchError` operator from `rxjs` to catch and handle errors from HTTP requests.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data').pipe(
catchError(error => {
console.error('Error occurred', error);
return of([]);
})
);
}
}
The `providers` property in `@NgModule` is used to define the services that will be available for dependency injection within the module.
import { NgModule } from '@angular/core';
import { MyService } from './my.service';
@NgModule({
providers: [MyService]
})
export class MyModule {}
The `*ngFor` directive is used to iterate over a list and create a template for each item in the list.
{{ item }}
The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on an expression.
Content is visible
The `@Input` decorator is used to pass data 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; }
The `AppComponent` is the root component of the Angular application and serves as the entry point for the component tree.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: '
Welcome to Angular!
' }) export class AppComponent {}
Custom directives are created by using the `@Directive` decorator to define a class that will be applied to elements.
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
}
The `ngOnInit` lifecycle hook is used for initialization logic that needs to be performed after the component's data-bound properties have been initialized.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
User input is handled using Angular forms, which can be either template-driven or reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
template: `
`
})
export class LoginComponent {
loginForm: FormGroup;
constructor(private fb: FormBuilder) {
this.loginForm = this.fb.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
onSubmit() {
console.log(this.loginForm.value);
}
}
The `ngModel` directive is used for two-way data binding between the form input fields and the component properties.
Hello {{ name }}
A custom pipe is defined by using the `@Pipe` decorator and implementing the `PipeTransform` interface.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
The `ngFor` directive is used to repeat a template for each item in a list or array.
{{ item }}
The `ngClass` directive is used to dynamically add or remove CSS classes based on the expression.
Styled text
The `@Output` decorator is used to define an event that a child component can emit to its parent component.
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');
}
}
You can bind a component property to an HTML element attribute using property binding syntax with square brackets.
The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on a boolean expression.
Content is visible
The `@ViewChild` decorator is used to access a child component or element within the component's template.
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 `@Injectable` decorator is used to mark a class as available for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
getValue() {
return 'Service value';
}
}
Reactive forms are created using the `FormBuilder` service to construct the form model and its controls.
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 `app.module.ts` file defines the root module of the application, including the components, directives, pipes, and services that are used throughout the app.
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 {}
Events are handled using Angular's event binding syntax, with parentheses around the event name.
The `ngSwitch` directive is used to conditionally display elements based on the value of an expression.
Case 1
Case 2
Default case
Child routes are defined within the `children` property of a route configuration object.
const routes: Routes = [
{ path: 'parent', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties of the component.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-example', template: '
{{ value }}
' }) export class ExampleComponent implements OnChanges { @Input() value: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
A service can be created using the `@Injectable` decorator with the `providedIn: 'root'` option to make it available throughout the application.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Some data';
}
}
The `ngStyle` directive is used to apply styles dynamically based on an expression.
Styled text
The `@HostListener` decorator is used to listen to events on the host element of the 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');
}
}
HTTP requests are handled using the `HttpClient` service provided by the `@angular/common/http` module.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-http', template: '
Check console for HTTP request result
' }) export class HttpComponent { constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .subscribe(data => console.log(data)); } }
The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables when a component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent implements OnDestroy { private subscription: Subscription; constructor() { this.subscription = // ... initialize subscription } ngOnDestroy() { this.subscription.unsubscribe(); } }
The `ngModel` directive is used for two-way data binding between form input fields and component properties.
Hello {{ name }}
A custom pipe is defined by using the `@Pipe` decorator and implementing the `PipeTransform` interface.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
The `ngFor` directive is used to repeat a template for each item in a list or array.
{{ item }}
The `ngClass` directive is used to dynamically add or remove CSS classes based on the expression.
Styled text
The `@Output` decorator is used to define an event that a child component can emit to its parent component.
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');
}
}
You can bind a component property to an HTML element attribute using property binding syntax with square brackets.
The `ngIf` directive is used to conditionally include or exclude elements from the DOM based on a boolean expression.
Content is visible
The `@ViewChild` decorator is used to access a child component or element within the component's template.
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 `@Injectable` decorator is used to mark a class as available for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
getValue() {
return 'Service value';
}
}
Reactive forms are created using the `FormBuilder` service to construct the form model and its controls.
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 `app.module.ts` file defines the root module of the application, including the components, directives, pipes, and services that are used throughout the app.
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 {}
Events are handled using Angular's event binding syntax, with parentheses around the event name.
The `ngSwitch` directive is used to conditionally display elements based on the value of an expression.
Case 1
Case 2
Default case
Child routes are defined within the `children` property of a route configuration object.
const routes: Routes = [
{ path: 'parent', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties of the component.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-example', template: '
{{ value }}
' }) export class ExampleComponent implements OnChanges { @Input() value: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
A service can be created using the `@Injectable` decorator with the `providedIn: 'root'` option to make it available throughout the application.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Some data';
}
}
The `ngStyle` directive is used to apply styles dynamically based on an expression.
Styled text
The `@HostListener` decorator is used to listen to events on the host element of the 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');
}
}
HTTP requests are handled using the `HttpClient` service provided by the `@angular/common/http` module.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-http', template: '
Check console for HTTP request result
' }) export class HttpComponent { constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .subscribe(data => console.log(data)); } }
The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables when a component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-example', template: '
Example component
' }) export class ExampleComponent implements OnDestroy { private subscription: Subscription; constructor() { this.subscription = // ... initialize subscription } ngOnDestroy() { this.subscription.unsubscribe(); } }
The `ngOnInit` lifecycle hook is used for component initialization, including fetching data and setting up component properties.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: '
{{ message }}
' }) export class ExampleComponent implements OnInit { message: string; ngOnInit() { this.message = 'Component initialized'; } }
The `ngModel` directive binds form control values to component properties, supporting two-way data binding in forms.
A service is defined with the `@Injectable` decorator and can be injected into components or other services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
Routing is configured using the `RouterModule.forRoot` method, providing route definitions in the application module.
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 {}
Validation is implemented using Angular’s built-in validators or custom validators on form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validation-form',
template: `
`
})
export class ValidationFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
if (this.form.valid) {
console.log(this.form.value);
}
}
}
When using `ngFor` with objects, you can iterate over the object's keys using the `keyvalue` pipe.
{{ item.key }}: {{ item.value }}
The `ngAfterViewInit` lifecycle hook is used to perform actions after Angular initializes the component's view and child views.
import { Component, AfterViewInit, ViewChild } 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('Child component:', this.child);
}
}
You can dynamically set CSS styles using Angular’s `[ngStyle]` directive.
Dynamic style content
A module is created using the `@NgModule` decorator and can include declarations, imports, providers, and bootstrap components.
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 `ngSwitch` directive allows you to display elements based on a matched value.
Case 1
Case 2
Default case
HTTP requests are handled using Angular’s `HttpClient` service.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; @Component({ selector: 'app-http', template: '
Data: {{ data }}
' }) export class HttpComponent { data: any; constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .subscribe(response => this.data = response); } }
The `@Input` decorator is used to define properties that can receive data from a parent component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: '
{{ data }}
' }) export class ChildComponent { @Input() data: string; }
The `ngClass` directive dynamically sets CSS classes on an element based on conditions.
Conditional classes
You can create a component using the Angular CLI command `ng generate component` or `ng g c`.
ng generate component my-component
The `ng-content` directive is used for content projection, allowing you to insert content into a component’s template.
@Component({
selector: 'app-wrapper',
template: ' '
})
export class WrapperComponent {}
The `@ViewChild` decorator is used to query a single child element or component.
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
@ViewChild(ChildComponent) child: ChildComponent;
}
The `@Output` decorator is used to define an event that a child component can emit to its parent component.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter();
sendMessage() {
this.messageEvent.emit('Hello from child');
}
}
Errors in HTTP requests can be handled using the `catchError` operator in RxJS.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Component({ selector: 'app-http', template: '
Data: {{ data }}
' }) export class HttpComponent { data: any; constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .pipe( catchError(error => { console.error('Error:', error); return of([]); }) ) .subscribe(response => this.data = response); } }
Routes with parameters are defined using a colon `:` followed by the parameter name.
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
The `ngOnDestroy` lifecycle hook is used to perform cleanup tasks when the component is destroyed.
import { Component, OnDestroy } from '@angular/core'; @Component({ selector: 'app-example', template: '
Component with cleanup
' }) export class ExampleComponent implements OnDestroy { ngOnDestroy() { console.log('Component destroyed'); } }
The `@Output` decorator is used to create custom events that a component can emit.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-custom-button',
template: ''
})
export class CustomButtonComponent {
@Output() clicked = new EventEmitter();
onClick() {
this.clicked.emit();
}
}
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-example',
template: ''
})
export class ExampleComponent {
@ViewChild('inputElement') input!: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
The `ngIf` directive is used to include or exclude elements based on a condition.
This content is visible
The `@Injectable` decorator is used to define a service that can be injected into components or other services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Data';
}
}
The `ngFor` directive can be used to iterate over objects by using the key-value pair syntax.
{{ key }}: {{ myObject[key] }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { myObject = { a: 1, b: 2, c: 3 }; objectKeys = Object.keys; }
The `@HostBinding` decorator is used to bind a property of the host element to a property in the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}
A custom pipe can be created to filter a list based on a condition.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'filterList' })
export class FilterListPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(item => item.toLowerCase().includes(searchText));
}
}
The `@ContentChild` decorator is used to get a reference to a child element projected into the component's view.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: ' '
})
export class ParentComponent implements AfterContentInit {
@ContentChild('content') content!: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
The `@Input` decorator is used to pass data 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; }
The `ngClass` directive can be used to conditionally apply CSS classes based on a condition.
Content
The `@Inject` decorator is used to specify a dependency for injection when the type cannot be inferred.
import { Injectable, Inject } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
constructor(@Inject(String) private value: string) { }
}
The `ngModel` directive is used for two-way data binding in forms.
Value: {{ value }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { value = 'Initial value'; }
The `ng-template` directive defines a template that can be conditionally rendered.
This is a template
Content when condition is true
The `ngOnChanges` lifecycle hook is used to detect and act upon changes to input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-example', template: '
{{ data }}
' }) export class ExampleComponent implements OnChanges { @Input() data!: string; ngOnChanges(changes: SimpleChanges) { console.log(changes); } }
The `ngOnInit` lifecycle hook is used to perform component initialization after Angular has initialized all data-bound properties.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: '
Component initialized
' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
The `ngSwitch` directive is used to conditionally display elements based on a switch expression.
Case 1
Case 2
Default case
The `ngContainer` is used to group elements without adding extra DOM elements.
Content is visible
The `ngFor` directive is used to repeat a block of HTML for each item in an array.
{{ item }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngModel` directive is used for two-way data binding with form inputs.
Input value: {{ inputValue }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { inputValue = ''; }
The `@NgModule` decorator is used to define an Angular module, including its components, directives, and services.
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 `ngIf` directive is used to include or exclude a block of HTML based on a condition.
This content is conditionally rendered
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isVisible = true; }
The `ngOnInit` lifecycle hook is used to perform initialization logic after Angular has set all input properties.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: '
Component Initialized
' }) export class ExampleComponent implements OnInit { ngOnInit() { console.log('Component Initialized'); } }
The `ngClass` directive can be used to dynamically add or remove CSS classes based on conditions.
Content with dynamic classes
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isActive = true; }
To create a custom directive, you use the `@Directive` decorator and implement the directive logic.
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 `ngFor` directive is used to loop through an array and generate HTML for each item.
{{ item.name }} - {{ item.value }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = [
{ name: 'Item 1', value: 10 },
{ name: 'Item 2', value: 20 },
{ name: 'Item 3', value: 30 }
];
}
The `@Input` decorator allows you to pass data 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; }
The `@Output` decorator is used to define an event that a component can emit to its parent component.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-button',
template: ''
})
export class ButtonComponent {
@Output() clicked = new EventEmitter();
onClick() {
this.clicked.emit();
}
}
The `@NgModule` decorator defines an Angular module, including its components, directives, pipes, and services.
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 { }
Event binding is done using parentheses around the event name in the template.
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
handleClick() {
console.log('Button clicked');
}
}
The `ng-container` is used to group elements without adding extra DOM elements.
Content is visible
Form validation is handled using `FormGroup` and `FormControl` with built-in or custom 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],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
if (this.form.valid) {
console.log(this.form.value);
}
}
}
The `@HostListener` decorator is used 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 `HttpClient` service is used to make HTTP requests to a server and handle responses.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-data',
template: '...',
})
export class DataComponent {
constructor(private http: HttpClient) {}
fetchData() {
this.http.get('https://api.example.com/data').subscribe(data => {
console.log(data);
});
}
}
The `ngOnDestroy` lifecycle hook is used to clean up resources, such as unsubscribing from observables or detaching event handlers, before a component is destroyed.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
this.subscription = someObservable.subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
The `ngModel` directive is used to bind form input values to component properties with two-way data binding.
Input value: {{ inputValue }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { inputValue = ''; }
The `@Injectable` decorator marks a class as available for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Data from service';
}
}
Routing in Angular is configured using the `RouterModule` and defining routes in a routing module.
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: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Create a service using `@Injectable`, then inject it into a component's constructor.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Data from service';
}
}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private exampleService: ExampleService) {
console.log(this.exampleService.getData());
}
}
Angular modules are classes with a `@NgModule` decorator that define a context for a set of components, directives, pipes, and services. You create a module using `@NgModule`.
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 `@Pipe` decorator defines a custom pipe for transforming 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('');
}
}
\
Use the Angular CLI command `ng generate component
ng generate component my-component
// The command creates a folder with four files:
// my-component.component.ts
// my-component.component.html
// my-component.component.css
// my-component.component.spec.ts
The `@Component` decorator is used to define a component, including its metadata like selector, template, and style URLs.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
// Component logic
}
Handle form submission by using the `(ngSubmit)` event in the template and handling it in the component.
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
onSubmit() {
console.log('Form submitted');
}
}
Use Angular's `*ngIf` directive to conditionally render elements based on a condition.
This content is conditionally rendered
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isVisible = true; }
The `@NgModule` decorator defines an Angular module, including declarations, imports, providers, and bootstrap components.
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 { }
Data binding is done using interpolation `{{}}`, property binding `[property]`, and event binding `(event)`.
{{ message }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { message = 'Hello, Angular!'; imageUrl = 'https://example.com/image.jpg'; handleClick() { console.log('Button clicked'); } }
The `ngFor` directive is used to repeat an element for each item in an array.
{{ item }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `@Injectable` decorator marks a class as available for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Data from service';
}
}
The `ngModel` directive enables two-way data binding by binding form input values to component properties.
Input value: {{ inputValue }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { inputValue = ''; }
Routes are defined using the `RouterModule` and specifying route configurations in a routing module.
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: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
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 `@Pipe` decorator defines a custom pipe for transforming 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('');
}
}
Inject a service into a component by adding it to the component's constructor.
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private exampleService: ExampleService) {
console.log(this.exampleService.getData());
}
}
Angular modules are classes annotated with `@NgModule` that group related components, directives, pipes, and services. They are used to organize an application into cohesive blocks.
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 `ngClass` directive allows you to dynamically add or remove CSS classes based on conditions.
Conditional styling
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isActive = true; }
Handle user input using Angular's forms module, either with template-driven forms or reactive forms.
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
Create a custom pipe by defining a class with the `@Pipe` decorator and implementing the `PipeTransform` interface.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
The `ngOnInit` lifecycle hook is used to initialize component properties and perform any necessary setup after the component's data-bound properties have been initialized.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnInit {
ngOnInit() {
console.log('Component initialized');
}
}
Pass data to a child component using `@Input` properties.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '...',
})
export class ChildComponent {
@Input() data: any;
}
The `@Output` decorator is used to emit events from a child component 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();
}
}
// Parent component template
@Component({
selector: 'app-parent',
template: '...',
})
export class ParentComponent {
onNotify() {
console.log('Notification received');
}
}
Use the Angular CLI command `ng generate component
ng generate component my-component
// The command creates a folder with four files:
// my-component.component.ts
// my-component.component.html
// my-component.component.css
// my-component.component.spec.ts
The `@Component` decorator is used to define a component, including its metadata like selector, template, and style URLs.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
// Component logic
}
Handle form submission by using the `(ngSubmit)` event in the template and handling it in the component.
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
onSubmit() {
console.log('Form submitted');
}
}
Use Angular's `*ngIf` directive to conditionally render elements based on a condition.
This content is conditionally rendered
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isVisible = true; }
The `@NgModule` decorator defines an Angular module, including declarations, imports, providers, and bootstrap components.
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 { }
Data binding is done using interpolation `{{}}`, property binding `[property]`, and event binding `(event)`.
{{ message }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { message = 'Hello, Angular!'; imageUrl = 'https://example.com/image.jpg'; handleClick() { console.log('Button clicked'); } }
The `ngFor` directive is used to repeat an element for each item in an array.
{{ item }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `@Injectable` decorator marks a class as available for dependency injection.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return 'Data from service';
}
}
The `ngModel` directive enables two-way data binding by binding form input values to component properties.
Input value: {{ inputValue }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { inputValue = ''; }
Routes are defined using the `RouterModule` and specifying route configurations in a routing module.
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: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
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 `@Pipe` decorator defines a custom pipe for transforming 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('');
}
}
Inject a service into a component by adding it to the component's constructor.
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private exampleService: ExampleService) {
console.log(this.exampleService.getData());
}
}
Angular modules are classes annotated with `@NgModule` that group related components, directives, pipes, and services. They are used to organize an application into cohesive blocks.
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 `ngClass` directive allows you to dynamically add or remove CSS classes based on conditions.
Conditional styling
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isActive = true; }
Handle user input using Angular's forms module, either with template-driven forms or reactive forms.
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
Create a custom pipe by defining a class with the `@Pipe` decorator and implementing the `PipeTransform` interface.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
The `ngOnInit` lifecycle hook is used to initialize component properties and perform any necessary setup after the component's data-bound properties have been initialized.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnInit {
ngOnInit() {
console.log('Component initialized');
}
}
Pass data to a child component using `@Input` properties.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '...',
})
export class ChildComponent {
@Input() data: any;
}
The `@Output` decorator is used to emit events from a child component 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();
}
}
// Parent component template
@Component({
selector: 'app-parent',
template: '...',
})
export class ParentComponent {
onNotify() {
console.log('Notification received');
}
}
Create a module using the Angular CLI command `ng generate module
ng generate module my-module
// Example of manually creating a module
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my.component';
@NgModule({
declarations: [MyComponent],
imports: [CommonModule],
exports: [MyComponent]
})
export class MyModule { }
Set up routing by defining routes in the `AppRoutingModule` and using the `
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: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
// In the main template
Implement lazy loading by configuring routes with the `loadChildren` property.
const routes: Routes = [
{ path: 'home', loadChildren: () => import('./home/home.module').then(m => m.HomeModule) },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
// In home-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent }
];
Angular services are classes that handle business logic and data access. They are used by injecting them into components or other services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return 'Data from service';
}
}
// Injecting service into a component
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private dataService: DataService) {
console.log(this.dataService.getData());
}
}
Perform HTTP requests using the `HttpClient` service.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
fetchData() {
return this.http.get('https://api.example.com/data');
}
}
// In the component
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
data: any;
constructor(private dataService: DataService) {
this.dataService.fetchData().subscribe(response => {
this.data = response;
});
}
}
The `ngIf` directive conditionally includes or excludes elements in the DOM based on an expression.
This content is visible
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isVisible = true; }
The `ngFor` directive repeats an element for each item in an array.
{{ item }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `@Output` decorator is used to create custom events that components can emit to notify their parent components.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: '',
})
export class ChildComponent {
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit();
}
}
// In the parent component
@Component({
selector: 'app-parent',
template: '...',
})
export class ParentComponent {
onNotify() {
console.log('Notification received');
}
}
The `@Input` decorator is used to pass data 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; } // In the parent component @Component({ selector: 'app-parent', template: '
', }) export class ParentComponent { parentData = 'Data from parent'; }
Modules in Angular are used to organize an application into cohesive blocks. They help in managing and encapsulating components, services, directives, and pipes.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MyModule } from './my.module';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, MyModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Form validation in Angular can be handled using built-in validators or custom validators in both template-driven and reactive forms.
// Reactive form
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
if (this.form.valid) {
console.log(this.form.value);
}
}
}
Create custom directives to extend the behavior of elements in your application.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) { } @HostListener('mouseover') onMouseOver() { this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow'); } @HostListener('mouseout') onMouseOut() { this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor'); } } // In the component template
Hover over me!
Angular's change detection strategy determines how and when the view updates. The default strategy is `CheckAlways`, but it can be customized to `OnPush` for performance optimization.
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent { }
Implement dependency injection by providing services in Angular modules or components and injecting them into constructors.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return 'Data from service';
}
}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private dataService: DataService) {
console.log(this.dataService.getData());
}
}
Angular provides built-in pipes for formatting data in templates, such as `DatePipe`, `CurrencyPipe`, and `DecimalPipe`.
{{ today | date:'shortDate' }}
{{ amount | currency:'USD' }}
{{ number | number:'1.2-2' }}
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { today = new Date(); amount = 1234.56; number = 1234.5678; }
State management in Angular can be handled using services, or more advanced solutions like NgRx for large applications.
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);
}
}
// In the component
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
state$ = this.stateService.state$;
constructor(private stateService: StateService) { }
updateState() {
this.stateService.setState({ key: 'value' });
}
}
Handle errors in HTTP requests by using the `catchError` operator from RxJS and handling them in the service.
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
fetchData() {
return this.http.get('https://api.example.com/data').pipe(
catchError(error => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}
}
The `ngOnDestroy` lifecycle hook is used to perform cleanup before the component is destroyed.
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}
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: MouseEvent) {
console.log('Element clicked:', event);
}
}
The `ngStyle` directive allows you to set multiple inline styles dynamically based on an expression.
Dynamic styling
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isRed = true; fontSize = 16; }
The `ngClass` directive allows you to dynamically add or remove CSS classes based on an expression.
Dynamic classes
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isActive = true; isDisabled = false; }
Angular guards are used to protect routes and control access. They can be implemented using interfaces such as `CanActivate`, `CanDeactivate`, `Resolve`, and `CanLoad`.
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 actual authentication check
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
// In app-routing.module.ts
const routes: Routes = [
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
The `@ContentChild` and `@ContentChildren` decorators are used to access content projected into a component using `ng-content`.
import { Component, ContentChild, ContentChildren, QueryList, AfterContentInit } from '@angular/core'; import { ElementRef } from '@angular/core'; @Component({ selector: 'app-parent', template: '
', }) export class ParentComponent implements AfterContentInit { @ContentChild('header') header: ElementRef; @ContentChildren('item') items: QueryList ; ngAfterContentInit() { console.log(this.header.nativeElement.textContent); this.items.forEach(item => console.log(item.nativeElement.textContent)); } } // In the parent component template
Header
Item 1
Item 2
`Renderer2` is an Angular service used to manipulate the DOM in a way that is safe and compatible with different platforms.
import { Renderer2, ElementRef, AfterViewInit } from '@angular/core'; import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: '
', }) export class ExampleComponent implements AfterViewInit { constructor(private renderer: Renderer2, private el: ElementRef) { } ngAfterViewInit() { const div = this.el.nativeElement.querySelector('div'); this.renderer.setStyle(div, 'color', 'red'); } }
`FormArray` is used to manage an array of form controls or form groups. It allows dynamic addition and removal of form elements.
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
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);
}
}
Use `NgModule` imports to include other modules in your module and exports to make components, directives, or pipes available outside the module.
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [MyComponent],
exports: [MyComponent]
})
export class MyModule { }
`@ViewChild` and `@ViewChildren` are used to access elements or components within the component's view.
import { Component, ViewChild, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-example', template: `
Paragraph 1
Paragraph 2
`, }) export class ExampleComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; @ViewChildren('paragraph') paragraphs: QueryList
; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); this.paragraphs.forEach(p => console.log(p.nativeElement.textContent)); } }
Angular pipes transform data in templates. You can create custom pipes by implementing the `PipeTransform` interface.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'reverse' }) export class ReversePipe implements PipeTransform { transform(value: string): string { return value.split('').reverse().join(''); } } // In the component template
{{ 'Hello' | reverse }}
Lifecycle hooks are methods that Angular calls at different stages of a component's lifecycle, such as `ngOnInit`, `ngOnChanges`, `ngOnDestroy`, etc.
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component initialized');
}
ngOnDestroy() {
console.log('Component destroyed');
}
}
The `ChangeDetectorRef` service is used to manually trigger change detection.
import { ChangeDetectorRef, Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private cdr: ChangeDetectorRef) { }
triggerChangeDetection() {
this.cdr.detectChanges();
}
}
Form validation in Angular is handled using validators on form controls or form groups. Validators can be synchronous or asynchronous.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]]
});
}
get name() {
return this.form.get('name');
}
onSubmit() {
if (this.form.valid) {
console.log(this.form.value);
}
}
}
Use `HttpInterceptor` to intercept HTTP requests and responses for tasks such as adding headers or logging.
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 token')
});
return next.handle(authReq);
}
}
// In app.module.ts
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
The `@Input` decorator allows a component to receive data from its parent, and the `@Output` decorator allows a component to emit events to its parent.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Input() message: string;
@Output() notify: EventEmitter = new EventEmitter();
notifyParent() {
this.notify.emit('Hello from child');
}
}
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent {
parentMessage = 'Message from parent';
onNotify(message: string) {
console.log(message);
}
}
Create a lazy-loaded module by using the `loadChildren` property in the routing configuration.
const routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}
];
Use `NgModule` to organize an application into cohesive blocks of functionality, which helps with code organization and reusability.
@NgModule({
declarations: [Component1, Component2],
imports: [CommonModule, FormsModule],
exports: [Component1]
})
export class SharedModule { }
`ViewEncapsulation` controls how styles are encapsulated within a component. Options include `Emulated`, `Native`, and `None`.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
styles: [`p { color: red; }`],
encapsulation: ViewEncapsulation.None
})
export class ExampleComponent { }
The `async` pipe automatically subscribes to an observable or promise and returns the latest value.
@Component({ selector: 'app-example', template: `
{{ data$ | async }}
`, }) export class ExampleComponent { data$ = this.dataService.getData(); constructor(private dataService: DataService) { } }
The `ngFor` directive is used to repeat a block of HTML for each item in an array or list.
{{ item }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
The `ngIf` directive conditionally includes or excludes a block of HTML based on an expression.
Visible content
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { isVisible = true; }
The `ngSwitch` directive allows you to conditionally include one of multiple elements based on a value.
Case A
Case B
Default case
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { selectedValue = 'A'; }
The `@Injectable` decorator marks a class as available to be provided and injected as a dependency.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class ExampleService {
constructor() { }
}
`NgZone` is used to execute code inside or outside Angular's zone to control change detection.
import { NgZone } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private ngZone: NgZone) { }
runOutsideAngular() {
this.ngZone.runOutsideAngular(() => {
// Code here will not trigger Angular's change detection
});
}
}
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: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
`@ViewEncapsulation` controls how styles are applied to the component's view. It can be `Emulated`, `Native`, or `None`.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-example', template: `
Styled text
`, styles: [`p { color: green; }`], encapsulation: ViewEncapsulation.Emulated }) export class ExampleComponent { }
`Renderer2` is a service for safely manipulating the DOM.
import { Component, Renderer2, ElementRef, OnInit } from '@angular/core'; @Component({ selector: 'app-example', template: `
`, }) export class ExampleComponent implements OnInit { constructor(private renderer: Renderer2, private el: ElementRef) { } ngOnInit() { const div = this.el.nativeElement.querySelector('div'); this.renderer.setStyle(div, 'color', 'blue'); } }
`HttpClient` is used to make HTTP requests and handle responses.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
constructor(private http: HttpClient) { }
fetchData() {
this.http.get('https://api.example.com/data').subscribe(data => {
console.log(data);
});
}
}
`NgModule` is used to organize an Angular application into cohesive blocks of functionality.
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create a custom directive 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');
}
}
`ngOnInit` is used for component initialization, while `ngOnChanges` is used to respond to changes in input properties.
import { Component, OnInit, OnChanges, SimpleChanges, Input } from '@angular/core';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent implements OnInit, OnChanges {
@Input() data: string;
ngOnInit() {
console.log('Component initialized');
}
ngOnChanges(changes: SimpleChanges) {
console.log('Input properties changed', changes);
}
}
`FormBuilder` simplifies the creation of reactive forms.
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
console.log(this.form.value);
}
}
`@Input` allows a parent component to pass data to a child component, and `@Output` allows a child component to emit events to a parent component.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Input() childData: string;
@Output() notify: EventEmitter = new EventEmitter();
notifyParent() {
this.notify.emit('Data from child');
}
}
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent {
parentData = 'Data from parent';
handleNotify(data: string) {
console.log(data);
}
}
Use Angular's Router module to define routes and navigate between different views.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', redirectTo: 'home' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Create a feature module to encapsulate related components, directives, and services.
@NgModule({
declarations: [FeatureComponent],
imports: [CommonModule, SharedModule],
exports: [FeatureComponent]
})
export class FeatureModule { }
`@ViewChild` allows you to access a child component or directive, and `@ContentChild` allows you to access projected content.
import { Component, ViewChild, ContentChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-example', template: `
Content
`, }) export class ExampleComponent { @ViewChild('paragraph') paragraph: ElementRef; @ContentChild('content') content: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } ngAfterContentInit() { console.log(this.content.nativeElement.textContent); } }
`ngStyle` is used to dynamically set multiple inline styles for an element.
@Component({ selector: 'app-example', template: `
Styled text
`, }) export class ExampleComponent { color = 'blue'; fontSize = '20px'; }
`ngClass` is used to dynamically add or remove CSS classes from an element based on conditions.
@Component({ selector: 'app-example', template: `
Classy div
`, }) export class ExampleComponent { isActive = true; }
`ngFor` can be used to iterate over objects by using the `keyvalue` pipe.
{{ entry.key }}: {{ entry.value }}
@Component({
selector: 'app-example',
template: '...',
})
export class ExampleComponent {
object = { name: 'John', age: 30 };
}
`ngTemplateOutlet` is used to dynamically insert an `
Template content
@Component({ selector: 'app-example', template: '...', }) export class ExampleComponent { }
`ngContent` is used to project content into a component's template.
@Component({ selector: 'app-example', template: `
`, }) export class ExampleComponent { } @Component({ selector: 'app-parent', template: `
Projected content
`, }) export class ParentComponent { }
`@HostBinding` is used to bind properties of the host element to component or directive properties.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}