This blog will provide a detailed guide to the core Angular concepts, including the following:
1.Introduction to Angular
2.Components
- Component Lifecycle
- Component Communication
- Data Binding
3.Templates
- Template Syntax
- Structural Directives
- Attribute Directives
- Template Reference Variables
- Pipes
4.Directives
- Built-in Angular Directives
- Custom Directives
1.Introduction to Angular
Angular is a powerful TypeScript-based framework used to build single-page applications (SPAs). It provides tools for managing components, templates, routing, services, and more. The primary building block of Angular applications is the Component, which is responsible for displaying content and handling user interactions.
2.Components
1.Component Lifecycle
Angular lifecycle hooks are methods that allow developers to tap into key moments of an Angular component’s life cycle, from its creation to its destruction which includes initialization, changes, and destruction. The most commonly used lifecycle hooks are:
- Constructor: Called when page loads at first time. Called only one time.
- ngOnChanges: Execute multiple times. first time will execute when component created/loaded. When there is change in custom property with @input decorator that every time this hook will called. worked with argument - simple changes
- ngOnInit: Called once the component is initialized. Ideal for setting up the component’s state.
- ngDoCheck: Used to detect changes manually (called with each change detection cycle).
- ngAfterContentInit: Called after the content is projected into the component.
- ngAfterContentChecked: Called after the projected content is checked.
- ngAfterViewInit: Called after the view has been initialized.
- ngAfterViewChecked: Called after Angular checks the component’s view.
- ngOnDestroy: Called just before the component is destroyed. Use it to clean up resources, like unsubscribing from observables.
Before dive in, lets create prerequisite project:
We will need parent and child component. We will have Input field in parent component and will pass that inputed value to the child and will show in child component.
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
value:string = '';
SubmitValue(val: any) {
this.value = val.value;
}
}
parent.component.html
<h1>Lifecycle Hooks</h1>
<input type="text" placeholder="Input here..." #val>
<button (click)="SubmitValue(val)">Submit Value</button>
<br><br>
<app-child [inputValue]="value"></app-child>
child.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {
}
}
child.component.html
<div>
Input Value: <strong>{{inputValue}}</strong>
</div>
We will have output like this:
1.Constructor
- The constructor is a TypeScript class method used to initialize a component. It is called before any Angular lifecycle hooks.
- Primary use: Initialize dependency injection and set up variables.
export class ChildComponent implements OnInit {
constructor() {
**console.log("Constructor Called");**
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {}
}
2.ngOnChanges
- Invoked when any input properties of a component are changed.
- Provides a
SimpleChanges
object containing the previous and current values of the input properties. - Usage: Update the data input property from the parent component to trigger this hook.
export class ChildComponent implements OnInit, OnChanges {
constructor() {
console.log("Constructor Called");
}
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called");
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {}
}
Again I have inputed the value and again ngOnChanges called but constructor only called once.
Let's see what we have in changes argument:
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called", changes);
}
Let's put some value and see:
3.ngOnInit
- Called once after the first ngOnChanges.
- Primary use: Initialize the component and set up any necessary data for rendering.
export class ChildComponent implements OnInit, OnChanges {
constructor() {
console.log("Constructor Called");
}
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called");
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {
console.log("ngOnInit Called");
}
}
4.ngDoCheck
- Runs every time Angular detects a change in the component or its children.
- Use this for custom change detection logic.
export class ChildComponent implements OnInit, OnChanges, DoCheck {
constructor() {
console.log("Constructor Called");
}
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called", changes);
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {
console.log("ngOnInit Called");
}
ngDoCheck() {
console.log("ngDoCheck Called");
}
}
5.ngAfterContentInit
- Called once after content (e.g., ) is projected into the component.
child.component.html
<div>
Input Value: <strong>{{inputValue}}</strong>
<ng-content></ng-content>
</div>
parent.component.html
<app-child [inputValue]="value"> Content </app-child>
child.component.ts
export class ChildComponent implements OnInit, OnChanges, DoCheck, AfterContentInit {
constructor() {
console.log("Constructor Called");
}
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called", changes);
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {
console.log("ngOnInit Called");
}
ngDoCheck() {
console.log("ngDoCheck Called");
}
ngAfterContentInit() {
console.log("ngAfterContentInit Called");
}
}
6.ngAfterContentChecked
- Called after every check of the projected content.
- Use sparingly to avoid performance issues.
export class ChildComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked {
constructor() {
console.log("Constructor Called");
}
ngOnChanges(changes: SimpleChanges): void {
console.log("ngOnChanges Called", changes);
}
@Input() inputValue: string = "LifeCycle Hooks";
ngOnInit(): void {
console.log("ngOnInit Called");
}
ngDoCheck() {
console.log("ngDoCheck Called");
}
ngAfterContentInit() {
console.log("ngAfterContentInit Called");
}
ngAfterContentChecked(): void {
console.log("ngAfterContentChecked Called");
}
}
let's play around this:
<app-child [inputValue]="value"> Content: {{value}} </app-child>
When there is change in ng-content again ngAfterContentChecked called.
7.ngAfterViewInit
- Called once after the component's view and its child views have been initialized.
- Useful for initializing third-party libraries or DOM manipulations.
8.ngAfterViewChecked
- Invoked after every check of the component's view and its child views.
9.ngOnDestroy
- Called just before the component is destroyed.
- Use it for cleanup tasks like unsubscribing from Observables or detaching event listeners.
ngOnDestroy will only called when we destroy any component, so let's try to remove child component when we click Destroy component button.
Let's make arrangmenets:
parent.component.ts
export class ParentComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
value:string = '';
childExist: boolean = true;
SubmitValue(val: any) {
this.value = val.value;
}
destroyComponet() {
this.childExist = false;
}
}
parent.component.html
<h1>Lifecycle Hooks</h1>
<input type="text" placeholder="Input here..." #val>
<button (click)="SubmitValue(val)">Submit Value</button>
<br><br>
<app-child *ngIf="childExist" [inputValue]="value"> Content: {{value}} </app-child>
<br><br>
<button (click)="destroyComponet()">Destroy component</button>
Before we click the Destroy component button:
After we click the Destroy component button:
Lifecycle Hook Sequence:
- Constructor
- ngOnChanges (if @Input properties exist)
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
By understanding and using these hooks effectively, you can manage the component's behavior at different stages of its lifecycle.
2.Component Communication
Components in Angular communicate with each other using @Input(), @Output(), and Event Emitters.
- @Input() allows a parent component to pass data to a child component.
- @Output() allows a child component to emit an event to the parent component.
Code Example:
Parent Component:
@Component({
selector: 'app-parent',
template: `
<app-child [message]="parentMessage" (messageEvent)="receiveMessage($event)"></app-child>
<p>Message from child: {{ receivedMessage }}</p>
`,
})
export class ParentComponent {
parentMessage = 'Hello from Parent!';
receivedMessage: string;
receiveMessage(message: string) {
this.receivedMessage = message;
}
}
Child Component:
@Component({
selector: 'app-child',
template: `
<p>{{ message }}</p>
<button (click)="sendMessage()">Send Message to Parent</button>
`,
})
export class ChildComponent {
@Input() message: string;
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
}
Output:
The parent component passes a message to the child component using @Input().
The child component sends an event to the parent using @Output() and EventEmitter.
3.Data Binding
Angular supports three types of data binding:
1.Property Binding: Bind component data to an HTML element's property.
<img [src]="imageUrl">
2.Event Binding: Bind an event in the component to an HTML element’s event
<button (click)="onClick()">Click Me</button>
3.Two-way Binding: Use [(ngModel)] to bind data in both directions.
<input [(ngModel)]="username">
3. Templates
Template Syntax
Angular templates are written in HTML, with some additional syntax for directives and bindings:
Interpolation: {{ expression }}
Display the result of an expression.Directives: Special markers in the template (e.g., *ngIf, *ngFor).
Structural Directives
1.ngIf: Conditionally render elements based on an expression.
<div *ngIf="isVisible">This is visible</div>
2.ngFor: Iterate over a list.
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
Attribute Directives
1.ngClass: Dynamically add/remove CSS classes.
<div [ngClass]="{'highlight': isHighlighted}">Text</div>
2.ngStyle: Dynamically set styles.
<div [ngStyle]="{'color': textColor}">Styled Text</div>
Template Reference Variables and Local Templates
- Template Reference Variables: Reference elements in the template.
<input #myInput>
<button (click)="myInput.focus()">Focus</button>
- Local Templates: Define reusable templates within the same component.
<ng-template #template1>
<p>This is a local template</p>
</ng-template>
Pipes
Pipes transform data before displaying it in the template.
- Only use in Html file
- In Angular 1 filters were used which are later called Pipes onwords Angular2.
- It is denoted by symbol |
- pipes used to transform the data.
- transform data before displaying in the views
- syntax: {{ ANGULAR | lowercase }}
- takes integer, strings, array, and date as input separated with | to be converted in the format as required and display in the browser.
1.Built-in Pipes:
- date: Formats date values.
- currency: Formats numbers as currency.
- uppercase: Transforms text to uppercase.
//--------------1. uppercase
msg="Learning never ends"
<h2>{{ msg | uppercase}}</h2>
//--------------2. lowercase
msg="LEARNING NEVER ENDS"
<h2>{{ msg | lowercase}}</h2>
//--------------3. titlecase
msg="LEARNING NEVER ENDS"
<h2>{{ msg | titlecase}}</h2>
//--------------4. slice
msg="LEARNING NEVER ENDS"
<h2>{{ msg | slice:3}}</h2>
<h2>{{ msg | slice:3:6}}</h2>
//--------------5. json
person = {
name: "renuka",
age: 25
}
<h2>{{ person | json}}</h2>
//--------------6. Date
myDate = new Date();
months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
<h2>{{ myDate | date}}</h2>
<h2>{{ myDate | date : 'short'}}</h2>
<h2>{{ myDate | date : 'medium'}}</h2>
<h2>{{ myDate | date : 'long'}}</h2>
<h2>{{ myDate | date : 'full'}}</h2>
<h2>{{ myDate | date : 'shortDate'}}</h2>
<h2>{{ myDate | date : 'mediumDate'}}</h2>
<h2>{{ myDate | date : 'longDate'}}</h2>
<h2>{{ myDate | date : 'fullDate'}}</h2>
<h2>{{ myDate | date : 'shortTime'}}</h2>
<h2>{{ myDate | date : 'mediumTime'}}</h2>
<h2>{{ myDate | date : 'longTime'}}</h2>
<h2>{{ myDate | date : 'fullTime'}}</h2>
<h2>{{ myDate | date : 'h'}}</h2>
<h2>{{ myDate | date : 'm'}}</h2>
<h2>{{ myDate | date : 's'}}</h2>
<h2>{{ myDate | date : 'a'}}</h2>
<h2>{{ myDate | date : 'h:m:s a'}}</h2>
<h2>{{ myDate | date : 'd'}}</h2>
<h2>{{ myDate | date : 'M'}}</h2>
<h2>{{ myDate | date : 'y'}}</h2>
<h2>{{ myDate | date : 'W'}}</h2>
<h2>{{ myDate | date : 'w'}}</h2>
*Custom Pipes *
Define your own transformation logic.
Angular makes provision to create custom pipes that convert the data in the format that you desire.
Angular pipes are Typescript classes with the @Pipe decorator
The decorator has a name property in its metadata that specifies the pipe and how and where it is used.
@Pipe({
name: 'custom' //name of our pipe
})
export class CustomPipe implements PipeTransform {
transform(value: number, ...args: unknown[]): unknown {
return value+2;
}
}
html file
<h2>{{ 2 | custom }}</h2
with one parameter:
@Pipe({
name: 'custom' //name of our pipe
})
export class CustomPipe implements PipeTransform {
transform(value: number, ...args: number[]): unknown {
const [a] = args;
return Math.pow(value, a);
}
html file
<h2>{{ 2 | custom: 3 }}</h2>
With 2 parameter:
@Pipe({
name: 'custom' //name of our pipe
})
export class CustomPipe implements PipeTransform {
transform(value: number, ...args: number[]): unknown {
const [a, b] = args;
return value + a + b;
}
html file
<h2>{{ 2 | custom: 3: 2 }}</h2>
Let's not use array when we want to pass only 1 parameter:
@Pipe({
name: 'custom' //name of our pipe
})
export class CustomPipe implements PipeTransform {
transform(value: number, num: number[]): unknown {
const a = num;
return value+a;
}
html file
<h2>{{ 2 | custom: 3 }}</h2>
4.Directives
Built-in Directives
Angular provides several built-in directives for managing templates:
- ngIf: Conditionally include elements in the DOM.
- ngFor: Repeat elements in the DOM for each item in a list.
- ngSwitch: Conditional rendering based on a value.
Custom Directives
Custom directives can be used to extend the functionality of Angular. They can be attribute or structural directives.
1.Attribute Directives: Modify the appearance or behavior of elements.
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
2.Structural Directives: Modify the structure of the DOM.
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
@Input() set appUnless(condition: boolean) {
if (!condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
}
You can see these blogs to cover all angular concepts:
Top comments (1)
Hi Renuka Patil,
Very nice and helpful !
Thanks for sharing.