Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE.eu :: Autofocus Directive in Angular

clock December 20, 2023 05:50 by author Peter

We will discover how to create a custom autofocus directive in an Angular application in this tutorial.


Required conditions
Basic familiarity with Angular 2 or later; installation of Node and NPM; Visual Studio Code; Bootstrap (Optional)

Make an Angular Project
The command to create an Angular project is as follows.
ng new angapp

Now install Bootstrap by using the following command,
npm install bootstrap --save

Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';


Create  Directive
Create  a new directive using the Angular CLI command
ng generate directive autofocus

Now open autofocus.directive.ts file and add following code
import { Directive, ElementRef, AfterViewInit } from '@angular/core';

@Directive({
  selector: '[Autofocus]'
})
export class AutofocusDirective implements AfterViewInit {
  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.el.nativeElement.focus();
  }
}


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    Autofocus Directive in Angular Application
  </div>
</div>
<div class="container">
  <input type="text" class="form-control" placeholder="Auto Focused Textbox" Autofocus />
</div>


Now open app.module.ts and following code
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AutofocusDirective } from './autofocus.directive';


@NgModule({
  declarations: [
    AppComponent, AutofocusDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }


Now run the application using npm start and check the result.

We discovered how to make a personalized autofocus directive in an Angular application by reading this post.



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Reverse String Pipe

clock December 15, 2023 06:50 by author Peter

We will discover how to build a pipe in an Angular application to reverse a string in this tutorial.


Required conditions
Basic familiarity with Angular 2 or later; installation of Node and NPM; Visual Studio Code; Bootstrap (Optional)

The command to create an Angular project is as follows.
ng new angapp

Now install Bootstrap by using the following command.
npm install bootstrap --save

Now open the styles.css file and add the Bootstrap file reference. To add a reference in the styles.css file, add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';

Create a Reverse String Pipe
Now, create a custom pipe by using the following command.
ng generate pipe Reverse

Now open the Reverse.pipe.ts file and add the following code.
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'reverseString' })
export class Reverse implements PipeTransform {
  transform(value: string): string {
    if (!value) return value;
    return value.split('').reverse().join('');
  }
}


Now, create a new component by using the following command.
ng g c actionmenu

Now open searchlist.actionmenu.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
    <p>{{ 'Artificial Intelligence' | reverseString }}</p>
</div>


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    Reverse String Pipe in Angular
  </div>
</div>
<app-actionmenu></app-actionmenu>


Now run the application using npm start and check the result:

 



AngularJS Hosting Europe - HostForLIFE.eu :: How Can I Use Angular Application to Detect Event on Clicks Outside?

clock December 12, 2023 07:01 by author Peter

Overview
This post will teach us how to recognize an event in an Angular application when a user clicks outside of a component.


Required conditions
Basic familiarity with Visual Studio Code, Angular 2 or higher, Node and NPM installed, and Bootstrap

Make an Angular Project
The command to create an Angular project is as follows.

ng new angapp

Now install Bootstrap by using the following command,
npm install bootstrap --save

Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';

Now create a new component by using the following command,
ng g c actionmenu

Now open actionmenu.component.html file and add the following code.
<div class="sidebar {{show}} panel-group" clickOutside (clickOutside)="works()">
    <div class=" panel panel-default" >
        <div>
            <div class="panel-body">Panel Body</div>
            <div class="panel-footer">Panel Footer</div>
        </div>
    </div>
</div>


Now open actionmenu.component.ts file and add the following code.
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-actionmenu',
  templateUrl: './actionmenu.component.html',
  styleUrls: ['./actionmenu.component.css']
})
export class ActionmenuComponent {
  @Input() show: boolean=true;

  works() {
    this.show = !this.show;
  }
}


Now open actionmenu.component.css file and add the following code.
.sidebar {
    display: none;
}

.true {
    display: block;
}

.false {
    display: none;
}


Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    How to detect clicks outside in Angular  Application
  </div>
</div>
<div class="container">
  <button type="button" class="btn btn-success" (click)="show = !show">Primary</button>
  <app-actionmenu [show]="show"></app-actionmenu>
</div>


Now open app.component.ts file and add the following code.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular App';
  show:boolean= false;
}


Now create a new directive by using the following command, and the following code in this directive.
ng g directive clickOutside

import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
    selector: '[clickOutside]'
})

export class ClickOutsideDirective {

    constructor(private elementRef: ElementRef) {}

    @Output() clickOutside: EventEmitter<any> = new EventEmitter();

    @HostListener('document: click', ['$event.target']) onMouseEnter(targetElement:any) {
        const clickInside = this.elementRef.nativeElement.contains(targetElement);
        if (!clickInside) {
            this.clickOutside.emit(null);
        }
    }
}

Now open app.module.ts and following code.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ActionmenuComponent } from './actionmenu/actionmenu.component';
import { ClickOutsideDirective } from './click-outside.directive';
@NgModule({
  declarations: [
    AppComponent,
    ActionmenuComponent,ClickOutsideDirective
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Now run the application using npm start and check the result.


Click outside anyplace in the component after clicking the button. This tutorial taught us how to detect events in the Compoent Angular application when a user clicks outside of any location.



Node.js Hosting Europe - HostForLIFE.eu :: TODO application with CQRS Design Pattern within Nest JS

clock December 4, 2023 08:53 by author Peter

A software design pattern called CQRS (Command Query Responsibility Segregation) divides up who is responsible for accessing and writing data in a system. The same set of components are frequently used in traditional design patterns for both reading and writing data. CQRS introduces two distinct models to suggest the division of these duties.

 

  • Command Model: The command model handles event triggering, data store updating, and command processing and validation.
  • Query Model: This model manages the processes involved in getting data out of the system.

The four major concepts of CQRS are listed below:

  • Command: Action or request to modify the system's status
  • Query: An occurrence or a request to obtain data from the system
  • Command Handler: An element in charge of processing commands and adjusting the system's state.
  • Query Handler: An element in charge of managing queries and getting information out of the system.

CQRS Offers Advantages like:

  • Scalability: Because the application supports several read and write data models, it can be scaled.
  • Flexibility: It permits the use of distinct data stores that are best suited for writing and reading processes.
  • Performance: There is room for improvement with this application.

This CQRS Model may be used with Nest JS; in this tutorial, we'll discover how to do it.

We'll use the creation and retrieval of a TODO application as an example using the CQRS paradigm.

Application for TODOs using CQRS pattern
You must use the command line to install nest cli if it is not already installed globally on your computer.
npm i -g @nestjs/cli

Create new Nest Js project if not created already using below command
nest new todo-application

Dependency Installation
Nest JS provides a package to implement CQRS, we need to install the package first using below command
npm install --save @nestjs/cqrs

Module Creation
Create new Module for our TODO application using command
nest generate module todo

Commands
Commands are used to change the application state, when a command is triggered, it is handled by corresponding command handler. Then handler will be responsible to process the operation. Every command will have command handler in order to process the command

Create new file inside todo module with name create-todo-command.ts and implement the below code
import { ICommand } from '@nestjs/cqrs';

export class CreateToDoCommand implements ICommand {
    constructor(
      public readonly title: string,
      public readonly description: string,
    ) {}
}

Command Handler
Create new file inside todo module with name create-todo-command-handler.ts  and implement the below code

import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';

@CommandHandler(CreateToDoCommand)
export class CreateToDoHandler implements ICommandHandler<CreateToDoCommand> {
  async execute(command: CreateToDoCommand): Promise<void> {
    // Add Logic to do validation and business rule
    const { title, description } = command;

    // Use Repository to save directly or Create Factory to add business logic and save
  }
}


Query
Queries are used to retrieve the data from the application, when a query is requested, Query handler handles the requests and retrieves the data. Every query will have query handler

Create new file inside todo module with name get-todo-query.ts  and implement the below code
import {  IQuery } from '@nestjs/cqrs';

export class GetToDoQuery implements IQuery {
    constructor() {}
}

Query Handler
Create new file inside todo module with name get-todo-query-handler.ts  and implement the below code
import { IQueryHandler, QueryHandler } from '@nestjs/cqrs';
import { GetToDoQuery } from './get-todo-query';

@QueryHandler(GetToDoQuery)
export class GetToDoQueryHandler implements IQueryHandler<GetToDoQuery> {
  async execute(query: GetToDoQuery): Promise<any> {
    // Fetch data using repository or factory and return it
    // Sample Response
    return [
      { id: 1, title: 'Test', description: 'Reminder to complete daily activity' },
      { id: 2, title: 'Test 2', description: 'Reminder to complete daily activity2' },
    ];
  }
}


Module
In the todo.module.ts  file, import the CQRS module to use the command handlers and query handlers
import { Module } from '@nestjs/common';
import { CqrsModule } from '@nestjs/cqrs';
import { ToDoController } from './todo.controller';
import { CreateToDoHandler } from './create-todo-command-handler';
import { GetToDoQueryHandler } from './get-todo-query-handler';

@Module({
  imports: [CqrsModule],
  controllers: [ToDoController],
  providers: [CreateToDoHandler, GetToDoQueryHandler],
})
export class ToDoModule {}


Controller
Create todo.controller.ts  file to handle the API request and use command and query bus
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CommandBus, QueryBus } from '@nestjs/cqrs';
import { CreateToDoCommand } from './create-todo-command';
import { GetToDoQuery } from './get-todo-query';

@Controller('ToDo')
export class ToDoController {
  constructor(
    private readonly commandBus: CommandBus,
    private readonly queryBus: QueryBus,
  ) {}

  @Post()
  async createToDo(@Body() body: { title: string, description: string }): Promise<void> {
    const { title, description } = body;
    await this.commandBus.execute(new CreateToDoCommand(title, description));
  }

  @Get()
  async getToDo(): Promise<any[]> {
    return this.queryBus.execute(new GetToDoQuery());
  }
}

Pro Tips
You can create a separate folder for command and query to segregate the code and make it more readable. Also, here I just gave the basic high level demo, but in your application, you can create dto for command and query, and you can directly use that dto
Conclusion

In conclusion, while CQRS can provide advantages in terms of scalability and flexibility, it comes with increased complexity and potential challenges in terms of consistency and development overhead. It is important to carefully consider whether the benefits align with the specific requirements and goals of the application being developed.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.




About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in