Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

How to use HostBinding and HostListener decorators in Ionic

Ionic hostbinding and ionic hostlistener

Ionic angular application is the use of an Angular framework to build ionic applications. An Angular provides a good range of built-in directives we can also create our own directives to solve problems that are specific to an application’s needs or to support features that the built-in directives don’t have. A directive is one of the core building blocks in Angular.

A directive is instructions or guidelines for rendering a template. It allows us to attach attributes to the element and with this attribute we can manipulate the appearance or behavior of a DOM element.

The @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives.

@HostBinding allows you to set the properties on the element or component that the host directive. Let’s say you want to change the style properties like the height of the host element. Here, you’d need to use the @HostBinding() decorator to access the property on the element and assign a value to the height on different events. Following are some of the examples where we use HostBinding to set properties like

  • @HostBinding(‘style.height’) height:string;
  • @HostBinding(‘style.color’) color: string;
  • @HostBinding(‘style.border-color’) borderColor: string;
  • @HostBinding(‘attr.role’) role = ‘button’;
  • @HostBinding(‘class.pressed’) isPressed: boolean;

HostBinding decorator takes one parameter, which is the name of the host element property. In the example below we have created two custom directives set properties as

  1. The height.directive.ts to set height properties of a div element on mouseover and mouseout event.
  2. The inputColorDirective.ts to set the random color on an input element on keydown events.
Ionic HostBinding and HostListener decorators

HostListener: The decorator that declares a DOM event to listen for and provides a handler method to run when that event occurs.

Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.

Ionic hostbinding and Ionic hostlistener project setup

Step 1: Create an ionic project

ionic start hostBindingApp blank --type=angular
cd hostBindingApp

Step 2: Create two custom directives as
Create a directive to change the height of a div element in home.page.html on mouseover and mouseout event.

ionic generate directive height

Add the following code to change the height.directive.ts file

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

@Directive({
  selector: '[appHeight]'
})
export class HeightDirective {
  @HostBinding('style.height') height: string;

  @HostListener('mouseover') onMouseOver() {
    this.height = '200px';
  }

  @HostListener('mouseout') onMouseOut() {
    this.height = '50px';
  }

}

We will create another example to set the random color on the input element border and font color properties. 

ionic generate directive inputColor

Add the following code in the inputColorDirective.ts file

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

@Directive({
  selector: '[appInputColor]'
})
export class InputColorDirective {

  availableColors = [
    'red', 'hotpink', 'yellow', 'gold', 'peachpuff',
    'mediumspringgreen', 'green', 'black', 'lightslategrey'
  ];

  @HostBinding('style.color') color: string;
  @HostBinding('style.border-color') borderColor: string;

  @HostListener('keydown') setColor() {
    const colorPick = Math.floor(Math.random() * this.availableColors.length);
    this.color = this.borderColor = this.availableColors[colorPick];
  }

}

Step 3: Move import of custom directive from app.module.ts to home.module.ts file
By default, while creating a directive by command line it will import both our custom directives in the app.module.ts file. We will remove both custom directives in the app.module.ts file and add them in our home.module.ts file as

import { NgModule } from '@angular/core';
import { HomePage } from './home.page';
import { InputColorDirective } from '../input-color.directive';
import { HeightDirective } from '../height.directive';
@NgModule({
  imports: [
   ...
  ],
  declarations: [
    HomePage,
    InputColorDirective,
    HeightDirective
  ]
})
export class HomePageModule {}

Step 4: Use both our custom directives on our home.page.html

ion-header>
  <ion-toolbar>
    <ion-title>
      Host binding
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding" appHeight style="background-color: blue;">
    <input type="text" appInputColor>
  </div>
</ion-content>

Related posts

How to use HostBinding and HostListener decorators in Ionic

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top