Sunday, June 4, 2023

Angular - @HostBinding and @HostListener

@HostBinding and @HostListener

Today, let's explore two powerful decorators in Angular: @HostBinding and @HostListener.The HostBinding and HostListener are decorators in Angular. HostListener listens to host events, while HostBinding allows us to bind to a property of the host element.

These decorators allow us to enhance the behavior of a component by interacting with its host element. Let's understand how they work and how we can effectively use them.

HostElement

The host element is the element on which we attach our directive or component. Remember components are directives with a view (template).

@HostBinding

The @HostBinding decorator enables us to bind a class property to a property of the host element. This way, we can dynamically modify the properties of the host element based on changes in our component's logic.

By utilizing this decorator, we can seamlessly update attributes, classes, or styles of the host element. Let's take a look at an example to illustrate the usage of @HostBinding:

import { Directive, HostBinding, OnInit } from '@angular/core';
@Directive({ selector: '[hostBindingExample]' })
export class HostBindingExampleDirective implements OnInit {
  @HostBinding('style.border') border: string = '';

  ngOnInit() {
    this.border = '5px solid green';
  }
}

In the above code snippet, hostBindingExample directive, uses the HostBinding on style.border property of the parent element to the border property.Whenever we change the value of the border, the angular will update the border property of the host element.

Sunday, May 28, 2023

Angular- Directive to Allow Number Only in Input Textbox

Directive to Allow Number Only in Input Textbox

In this post, we will create a directive which will allow only numbers to input textbox. User will not allow to enter any other value, only numbers.

Below is the code of directive which will check the input value and allow if the input value is number-

import { Directive, HostListener } from '@angular/core';

@Directive({ selector: '[allowNumberOnly]' })
export class AllowNumberOnly {
  readonly NUMBER_REGEX = '^[0-9]';
  @HostListener('keypress', ['$event'])
  onKeyPress(event: any): boolean {
    if (!new RegExp(this.NUMBER_REGEX).test(event.key)) {
      return false;
    }
    return true;
  }
}

To use the directive in application, we need to add the directive under declarations array of App Module file.

Monday, May 15, 2023

Basics of Web API- HTTP

Hyer-Text Transfer Protocol(HTTP)

  • HTTP(Hyer-Text Transfer Protocol) is a communication protocol on the web that is used to transmit data.
  • Extensible using Headers to send/receive extra information
  • Stateless, doesn’t maintain state unless using HTTP cookies to maintain the communication session or state.

HTTPS

S stands for secure, which means communication between client and server will happen via a secure channel using SSL\TLS encryption protocol.

TLS is the successor of SSL. TLS v1.3 is the latest version. The minimum recommended version of TLS is TLS v1.2, which the website should use to maintain a secure website.

HTTP Request Methods

  1. GET-Used to retrieve data. We can pass the parameter via query string to retrieve data based on the parameter.
  2. POST-Used to submit data within request body. This is usually used to pass personal or confidential data.
  3. PUT-Used to edit record to resource server without creating new record.
  4. DELETE-Used to delete a record in resource server.

Other methods are PATCH, OPTIONS, HEAD, TUNNEL, TRACE.

Content Types

  1. Plain-Data will be sent ‘as-is’ in plain text without any encryption, serialization or encoding.
  2. json-Data will be serialize in JSON format when sent from POST or PUT request body.
  3. form-url-encoded-This is represented as key-value pair of request parameter that are sent as request body.
  4. form-data-Used when uploading form fields that includes file upload. It uploads data in multiple parts. Use it when sending binary or large payload.

Tuesday, May 9, 2023

Angular - Bind Route Info to Component Inputs (Angular16)

Bind Route Info to Component Inputs in angulars

In building Angular application,most of the time we use the Router to render different pages for different urls, and based on the url we also load the data based on its path parameters or query parameters.

In the latest version of Angular v16, we will get a new feature that will simplify the process of retrieving route information in the component and make it way easier.Now we can bind route parameters to the corresponding component’s inputs

You can pass the following data to a routing component’s inputs-

  1. Route data — resolvers and data properties
  2. Path parameters
  3. Query parameters

We will be able to pass the route information to the component inputs, so we don’t need to inject the ActivatedRoute service anymore.

Below are some examples-

Route data — resolvers and data properties

// Routes
const routes: Routes = [
  {
    path: 'about',
    component: MyComponentComponent,
    resolve: { elementId: () => 'elementId1' },
  },
];
// Component Code
import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent implements OnInit {
  @Input() elementId: string = ''; //this will come from the resolved data
  ngOnInit(): void {
    console.log(this.elementId); // get elementId here
  }
}

Sunday, May 7, 2023

Angular- Required Component Inputs in Angular16

Required Component Inputs in Angular16

Angular16 has introduced a new feature to define the inputs as required for component and directives. We can now specify that a component or directive requires certain inputs to function properly.

By using this new feature, we can insure that all necessary data is present before the component or directive logic/functionality executed, resulting better code quality, fewer errors. To use it we can set the new required option in our input:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent {
  @Input({ required: true }) elementId: string;
}

There will be a compilation error if the consumer doesn’t initialize this input:

^ Scroll to Top