DEV Community

Renuka Patil
Renuka Patil

Posted on

1. Core Angular Concepts: Components, Templates, Data Binding, and Directives

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:

  1. Constructor: Called when page loads at first time. Called only one time.
  2. 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
  3. ngOnInit: Called once the component is initialized. Ideal for setting up the component’s state.
  4. ngDoCheck: Used to detect changes manually (called with each change detection cycle).
  5. ngAfterContentInit: Called after the content is projected into the component.
  6. ngAfterContentChecked: Called after the projected content is checked.
  7. ngAfterViewInit: Called after the view has been initialized.
  8. ngAfterViewChecked: Called after Angular checks the component’s view.
  9. ngOnDestroy: Called just before the component is destroyed. Use it to clean up resources, like unsubscribing from observables.

Image description

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;
  }

}

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 {
  }

}

Enter fullscreen mode Exit fullscreen mode

child.component.html

<div>
    Input Value: <strong>{{inputValue}}</strong>
</div>
Enter fullscreen mode Exit fullscreen mode

We will have output like this:

Image description

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 {}

}
Enter fullscreen mode Exit fullscreen mode

Image description

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 {}

}
Enter fullscreen mode Exit fullscreen mode

Image description

Again I have inputed the value and again ngOnChanges called but constructor only called once.

Image description

Let's see what we have in changes argument:

 ngOnChanges(changes: SimpleChanges): void {
    console.log("ngOnChanges Called", changes);
  }
Enter fullscreen mode Exit fullscreen mode

Image description

Let's put some value and see:

Image description

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");
  }

}
Enter fullscreen mode Exit fullscreen mode

Image description

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");
  }

}

Enter fullscreen mode Exit fullscreen mode

Image description

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>
Enter fullscreen mode Exit fullscreen mode

parent.component.html

<app-child [inputValue]="value"> Content </app-child>
Enter fullscreen mode Exit fullscreen mode

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");
  }

}

Enter fullscreen mode Exit fullscreen mode

Image description

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");
  }

}
Enter fullscreen mode Exit fullscreen mode

Image description

let's play around this:

<app-child [inputValue]="value"> Content: {{value}} </app-child>
Enter fullscreen mode Exit fullscreen mode

When there is change in ng-content again ngAfterContentChecked called.

Image description

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.

Image description

8.ngAfterViewChecked

  • Invoked after every check of the component's view and its child views.

Image description

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;

  }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Before we click the Destroy component button:

Image description

After we click the Destroy component button:

Image description

Lifecycle Hook Sequence:

  1. Constructor
  2. ngOnChanges (if @Input properties exist)
  3. ngOnInit
  4. ngDoCheck
  5. ngAfterContentInit
  6. ngAfterContentChecked
  7. ngAfterViewInit
  8. ngAfterViewChecked
  9. 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;
  }
}

Enter fullscreen mode Exit fullscreen mode

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!');
  }
}

Enter fullscreen mode Exit fullscreen mode

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">
Enter fullscreen mode Exit fullscreen mode

2.Event Binding: Bind an event in the component to an HTML element’s event

<button (click)="onClick()">Click Me</button>

Enter fullscreen mode Exit fullscreen mode

3.Two-way Binding: Use [(ngModel)] to bind data in both directions.

<input [(ngModel)]="username">
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

2.ngFor: Iterate over a list.

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

Enter fullscreen mode Exit fullscreen mode

Attribute Directives

1.ngClass: Dynamically add/remove CSS classes.

<div [ngClass]="{'highlight': isHighlighted}">Text</div>

Enter fullscreen mode Exit fullscreen mode

2.ngStyle: Dynamically set styles.

<div [ngStyle]="{'color': textColor}">Styled Text</div>

Enter fullscreen mode Exit fullscreen mode

Template Reference Variables and Local Templates

  • Template Reference Variables: Reference elements in the template.
<input #myInput>
<button (click)="myInput.focus()">Focus</button>

Enter fullscreen mode Exit fullscreen mode
  • Local Templates: Define reusable templates within the same component.
<ng-template #template1>
  <p>This is a local template</p>
</ng-template>

Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

*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;
  }

}

Enter fullscreen mode Exit fullscreen mode

html file

<h2>{{ 2 | custom }}</h2

Enter fullscreen mode Exit fullscreen mode

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);

}
Enter fullscreen mode Exit fullscreen mode

html file

<h2>{{ 2 | custom: 3 }}</h2>

Enter fullscreen mode Exit fullscreen mode

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;

}


Enter fullscreen mode Exit fullscreen mode

html file

<h2>{{ 2 | custom: 3: 2 }}</h2>

Enter fullscreen mode Exit fullscreen mode

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;

}
Enter fullscreen mode Exit fullscreen mode

html file

<h2>{{ 2 | custom: 3 }}</h2>

Enter fullscreen mode Exit fullscreen mode

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';
  }
}

Enter fullscreen mode Exit fullscreen mode

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) {}
}

Enter fullscreen mode Exit fullscreen mode

You can see these blogs to cover all angular concepts:

Beginner's Roadmap: Your Guide to Starting with Angular

  1. Core Angular Concepts
  2. Services and Dependency Injection
  3. Routing and Navigation
  4. Forms in Angular
  5. RxJS and Observables
  6. State Management
  7. Performance Optimization

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi Renuka Patil,
Very nice and helpful !
Thanks for sharing.