Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Connecting Angular Frontend to MongoDB via Express Backend

clock December 9, 2024 06:32 by author Peter

MongoDB With Angular Sample
Connecting MongoDB with an Express backend and an Angular frontend involves several steps. Here's a detailed guide, including a code sample, input/output, and steps.

Step 1. Set Up MongoDB
Install MongoDB

  • Install MongoDB locally or use a cloud solution like MongoDB Atlas.
  • Start the MongoDB server.

Create a Database

  • Use the MongoDB shell or a GUI tool like MongoDB Compass to create a database, e.g., my_database.
  • Add a collection, e.g., users.

Step 2. Create an Express Backend
Initialize the Project
mkdir express-mongodb-app
cd express-mongodb-app
npm init -y
npm install express mongoose body-parser cors


Create the Server File: Create a file named server.js.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// Middleware
app.use(cors());
app.use(bodyParser.json());

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/my_database', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

// Define Schema and Model
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
});
const User = mongoose.model('User', userSchema);
// Routes
app.get('/api/users', async (req, res) => {
    const users = await User.find();
    res.json(users);
});
app.post('/api/users', async (req, res) => {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json(newUser);
});
// Start Server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Run the Server
node server.js

Step 3. Create the Angular Frontend

Set Up Angular Project
ng new angular-mongodb-app
cd angular-mongodb-app
ng add @angular/material
npm install axios

Service for API Communication: Create a file src/app/services/user.service.ts.
import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({
    providedIn: 'root'
})
export class UserService {
    private baseUrl = 'http://localhost:3000/api/users';
    getUsers() {
        return axios.get(this.baseUrl);
    }
    addUser(user: { name: string; email: string }) {
        return axios.post(this.baseUrl, user);
    }
}


Component for User Interaction: Update src/app/app.component.ts.

typescript

import { Component, OnInit } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
    selector: 'app-root',
    template: `
        <div style="text-align: center;">
            <h1>Angular with Express & MongoDB</h1>
            <form (submit)="addUser($event)">
                <input type="text" [(ngModel)]="name" placeholder="Name" name="name" required>
                <input type="email" [(ngModel)]="email" placeholder="Email" name="email" required>
                <button type="submit">Add User</button>
            </form>
            <ul>
                <li *ngFor="let user of users">{{ user.name }} ({{ user.email }})</li>
            </ul>
        </div>
    `,
    styles: []
})
export class AppComponent implements OnInit {
    users: any[] = [];
    name = '';
    email = '';

    constructor(private userService: UserService) {}

    ngOnInit() {
        this.loadUsers();
    }

    async loadUsers() {
        const response = await this.userService.getUsers();
        this.users = response.data;
    }

    async addUser(event: Event) {
        event.preventDefault();
        await this.userService.addUser({ name: this.name, email: this.email });
        this.loadUsers();
        this.name = '';
        this.email = '';
    }
}


Install Angular Forms Module: Add FormsModule to AppModule.
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


Run the Angular Application
ng serve

Step 4. Input and Output
Input

Fill the form with a name and email, e.g.
Name: "Peter Scott"
Email: "[email protected]"

Output: The list below the form will update to include the newly added user.

less
Peter Scott ([email protected])

Step 5. Visual Workflow (Images)
Backend (server.js)

  • Database schema for storing user data.
  • APIs (/api/users) for CRUD operations.


Frontend (Angular App)

  • The user fills out the form.
  • Data is sent to the Express backend.
  • Data is saved in MongoDB.
  • Users are displayed dynamically.


AngularJS Hosting Europe - HostForLIFE :: Convert Doc to Pdf using NodeJS

clock December 5, 2024 08:53 by author Peter

To convert a DOC file to PDF using Node.js and PowerShell, you can use the following steps:
Install the ‘child_process’ package in your Node.js project by running the following command in your project’s terminal:

npm i child_process

Create a PowerShell script that converts the DOC file to PDF using Microsoft Word. You can use the following script:
$documents_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net.docx'
$output_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net12.pdf'
$word_app = New-Object -ComObject Word.Application
# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
    $document = $word_app.Documents.Open($_.FullName)
    $pdf_filename =  "$output_path"
    $document.SaveAs($pdf_filename)
    $document.Close()
}
$word_app.Quit()
return $output_path

Make sure to replace the input and output file paths with the actual paths to your files.
Use the ‘child_process’ package in your Node.js code to execute the PowerShell script. You can use the following code:
    const express =  require('express');
    const app =  express();
    const port = 5000;
    const { exec } = require('child_process');
    const { v4: uuidv4 } = require('uuid');
    const fileUpload = require('express-fileupload');
    const fs = require('fs');
    app.use(express.json({
        limit: "200mb"
      }));
      app.use(
        express.urlencoded({
          extended: true,
          limit: "200mb",
        })
      );


    app.use(fileUpload());

    app.post('/', function(req, res,next){
        console.log('req', req.files.inputfile)

        let uploaded_path = __dirname+'/doc/' + req.files.inputfile.name;
        fs.writeFile(uploaded_path, req.files.inputfile.data, function(err) {
            if(err) {
                return console.log(err);
            }
            ///console.log("The file was saved!");
            const cmd = `$documents_path = "${uploaded_path}"
            $output_path = '${__dirname}/doc/${uuidv4()}.pdf'
            $word_app = New-Object -ComObject Word.Application
            # This filter will find .doc as well as .docx documents
            Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
                $document = $word_app.Documents.Open($_.FullName)
                $pdf_filename = "$output_path"
                $document.SaveAs([ref] $pdf_filename, [ref] 17)
                $document.Close()
            }
            $word_app.Quit()
            return $output_path`;
            exec(cmd, {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
                console.log('Error', stderr)
                   console.log('OUTPUT', stdout);
                   res.status(200).json({status:200, msg:"success", stdout: stdout})
            })
        });

    })


    app.listen(port, function(){
        console.log('Server is running on port', port);
    })


Make sure to replace the script path and input file path with the actual paths to your files.
Run your Node.js code and the DOC file will be converted to PDF using PowerShell. The output PDF file will be saved to the path specified in the PowerShell script.



AngularJS Hosting Europe - HostForLIFE :: How Can I Use the Angular 18 Component to Call a JavaScript Function?

clock November 29, 2024 08:39 by author Peter

In this walk, you will learn about running and calling javascript functions from the Angular component.

How it’s implemented and what is the description?

  • Create Angular project - AnguWalk.
  • Run the application and check that the project was created successfully.
  • Create JS file with function.
  • Adding JS file link/reference to angular.json
  • Component (TS file) coding.
  • Execute the Project
  • Output

Create an Angular Project called “AnguWalk” using the following CLI command.Commandng new AnguWalkBashExample

Go inside the project folder and open the Visual Studio code.

Command
cd anguwalk
<enter>
code .
<enter>

Example

Note. Visual Studio code will get started only if your system is configured with path and settings.

Create Javascript file

  • First, create a JS folder inside the SRC folder.
  • Right-click on SRC and select the option New Folder.

    function HelloMsg(arg) {
        alert("Welcome to Angular Class - " + arg);
    }

Reference JS File in angular.json file
The Angular.json file is located inside the project root folder. Open and update the SCRIPTS array which is inside the builds object.

"scripts": [
    "src/js/WelcomeMsg.js"
]


Open app.component.html and update the code.

Note. Remove the default code of app.component.html.
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';

declare function HelloMsg(arg: any): void;

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  ngOnInit() {
    HelloMsg("Peter, Scott");
  }

  title = 'AnguWalk';
}

Now, run the project to check the output.

Command
ng serve --open

Output


You see the javascript HelloMsg function executed and the alert window displayed successfully. Happy Coding!



AngularJS Hosting Europe - HostForLIFE :: Debugging Angular Using Visual Studio Code

clock November 12, 2024 06:06 by author Peter

This brief post is meant for readers who are using Visual Studio Code to work on an Angular project and are having trouble adding a debugger. When I first started using Visual Studio Code to debug Angular projects, I thought it was rather strange, but eventually I thought it was cool. I discovered that many users were asking how to debug an Angular project in Visual Studio Code. I therefore considered composing this brief piece.

Note: I created and executed my Angular project, which internally uses WebPack, using the Angular CLI.

Step by Step add debugger in Visual Studio Code
Open your Angular project in Visual Studio Code.

Install Extension, as shown below.

Click Debug icon & Add Configuration, as shown below.

Select Chrome and add the configuration given below in launch.json file (This file gets created in .vscode folder).
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Chrome against localhost",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:4200",
            "sourceMaps": true,
            "webRoot": "${workspaceRoot}",
            "sourceMapPathOverrides": {
                "webpack:///./*": "${workspaceRoot}/*"
            }
        }
    ]
}

Open command terminal. As I am using Angular CLI to run my Angular project. I am using
> ng serve
command to build and run my application. By default, it runs on port 4200 (Same port is mentioned in my launch.json file).

Now, your development Server is running. Now, you can press F5 or play icon in the debug tab. Keep the break point and it will hit the .ts file.

Note.You may be surprised how JS can map my .ts file in code and debugger can hit my .ts file. This is because of "sourceMaps": true setting in launch.json. Similarly, we can add more debugger by adding an extension and then configuring in same launch.json file. I hope, this small article will be helpful to you. Please do comment, whether it’s good or bad. Sharing is valuable. Thank you for reading and have a great day.



AngularJS Hosting Europe - HostForLIFE :: Apply "Go to Bottom" and "Go Up" on Click of Anchors

clock November 5, 2024 08:47 by author Peter

In this article, I will tell you how to apply "Go to Bottom" and "Go Up" with a click of Anchors in an application. We often create single-page applications that are in great demand at the present time. In these applications, you might need a functionality by which the user can go to a different part of a page just by clicking on the link and not by scrolling. To do this kind of functionality, you can use AngularJS.


Now, I will create an application that will help you to create such an application.

Step 1. First of all, you need to add an external Angular.js file to your application, "angular.min.js". For this, you can go to the AngularJS official site or download my source code and then fetch it, or you can click on this link and download it: ANGULARJS. After downloading the external file, you need to add it to the Head section of your application.

<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
</head>


Step 2. Now, after adding the external JS file, the first thing you need to do is to add ng-app in the <HTML> Tag; otherwise, your application will not run.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">


Now, I will create a simple application that will help you understand this feature.

First I will create a JavaScript function, this is the heart of this article. All the things will be described in this function.
<script>
    function x($scope, $location, $anchorScroll) {
        $scope.goDown = function () {
            $location.hash('down');
            $anchorScroll();
        };

        $scope.goUp = function () {
            $location.hash('up');
            $anchorScroll();
        };
    }
</script>


Here I have created a function named "x", but today in the function $location and $anchorScroll are also used along with $scope. $location service parses the browser address bar and makes the URL available to your application.

Then I created a function that will help the user to go down just with the click of a link, this function is named "goDown". In this function a hash method is used with location, you can't change the "hash" method with any other variable name, it's fixed, and this has the method id of control that is passed to be followed on the click of the anchor.

Similarly, I have created a function that will help the user to go up, here also the hash method is used and in this method, the name of the control is passed that is to be followed when clicking the anchor.

Step 3. Our work on the View is completed, and now I will work on the View Model of this application.
<body>
    <form id="form1" runat="server">
        <div ng-app="App">
            <div id="div" ng-controller="x">
                <div style="color: green;">
                    <a id="up" ng-click="goDown()">Go Down</a>
                </div>
                <div style="color: red;">
                    <a id="down" ng-click="goUp()">You're at the bottom</a>
                </div>
            </div>
        </div>
    </form>
</body>


Here a div is bound to the function "x" using the ng-controller, in this div again two divs are created. In both the div anchors are used, the first anchor is bound to the "goDown" function using the ng-click, and the second anchor is also bound using the ng-click but it is bound to the group function.

Some style is also applied to this application, this style will help to show the two anchors at a specific distance by which only one will be seen at a time and the second one will only be seen when the user clicks on the anchor.

Now, our application is created and is ready for execution.

Output
Now, if we run our application, then we will get output like this.

You can see that only one anchor can be seen at this time and in other words the first anchor, now if we click on the first anchor then our page will go down to the element that was called using the JavaScript function.

Complete Code
The complete code of this application is as follows.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <script>
        function x($scope, $location, $anchorScroll) {
            $scope.goDown = function () {
                $location.hash('down');
                $anchorScroll();
            }
            $scope.goUp = function () {
                $location.hash('up');
                $anchorScroll();
            }
        }
    </script>
    <style>
        #div {
            height: 350px;
            overflow: auto;
        }
        #down {
            display: block;
            margin-top: 2000px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div ng-app="App">
            <div id="div" ng-controller="x">
                <div style="color:green;">
                    <a id="up" ng-click="goDown()">Go Down</a>
                </div>
                <div style="color:red;">
                    <a id="down" ng-click="goUp()">You're at the bottom</a>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

 



AngularJS Hosting Europe - HostForLIFE :: IoC Providers in Angular Dependency Injection useClass

clock October 9, 2024 09:04 by author Peter

Manual Injection of Class
Before we dive deep into Angular providers, let’s see how to create an Angular provider by ourselves. Please take a look at the below screenshot. We have created an interface named IManualService. We have two classes implementing the IManualService interface: ManualService and ManualServiceWithLog.

import { InjectionToken } from '@angular/core';
export const MANUAL_SERVICE_TOKEN = new InjectionToken<IManualService>(
  'MANUAL_SERVICE_TOKEN'
);
interface IManualService {
  name: string;
}
export class ManualService implements IManualService {
  public name = 'Manual Service';
  constructor() {}
}
export class ManualServiceWithLog implements IManualService {
  public name = 'Manual Service with logging feature';
  constructor() {
    console.log('I am manual service class with logging feature');
  }
}


For the dependency injection to work, we need to take care of three steps.
Define a Token: Define a token with a name for the injection. The token name is used by IoC to identify the class that needs to be injected whenever the particular token is requested.
    export const MANUAL_SERVICE_TOKEN = new InjectionToken<IManualService>(
      'MANUAL_SERVICE_TOKEN'
    );


Provide the Injection: The provider is the place where we define which class/value needs to be provided whenever we are requesting for a class/value.

Injecting ManualService class

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
  ManualServiceWithLog,
} from './services/manual-service/manual-service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    {
      provide: MANUAL_SERVICE_TOKEN,
      useClass: ManualService,
    },
  ],
};

Injecting ManualServiceWithLog class
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
  ManualServiceWithLog,
} from './services/manual-service/manual-service';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    {
      provide: MANUAL_SERVICE_TOKEN,
      useClass: ManualServiceWithLog,
    },
  ],
};

Inject the Token: Inject the token in our component or elsewhere wherever we are using it.
constructor(
   @Inject(MANUAL_SERVICE_TOKEN) private manualService: ManualService
 )

import { Component, Inject, Injectable } from '@angular/core';
import {
  MANUAL_SERVICE_TOKEN,
  ManualService,
} from '../services/manual-service/manual-service';

@Component({
  selector: 'app-books-cart',
  standalone: true,
  imports: [],
  templateUrl: './books-cart.component.html',
})
export class BooksCartComponent {
  value: string = '';
  constructor(
    @Inject(MANUAL_SERVICE_TOKEN) private manualService: ManualService
  ) {
    this.value = manualService.name;
  }
}


Once we take care of the above steps, we are ready with dependency injection. Since I am using Angular 18, the latest version, I am using app.config.ts to configure the providers. Here in this app.config.ts, for the key MANUAL_SERVICE_TOKEN, I am passing the ManualService class.

You can see the name ‘Manual Service’ populating from the ManualService class being printed in the UI. In the app.routes.ts class, instead of passing the ManualService class, if you pass the ManualServiceWithLog class, you can see that name being printed as ‘Manual Service with Logging Feature’. Along with that, we can even observe that the console is being logged.

UI Output while using ManualService Class


UI Output while using ManualServiceWithLog.


I hope from this example, you have understood how to use Dependency Injection in Angular and the use of useClass in providers.



AngularJS Hosting Europe - HostForLIFE :: How to Create Mobile App with Angular Ionic?

clock October 1, 2024 07:54 by author Peter

We will discover how to use the Ionic framework to construct a mobile application in this tutorial. With the help of the open-source Ionic user interface tool, which integrates with well-known frameworks like Angular, React, and Vue, we can create professional mobile applications with HTML, CSS, and JavaScript.


Both iOS and Android are supported.

Pre-requisite
To start with Ionic Framework, the only requirement is a Node & npm environment, Andriod Studio, command line interface, and Visual Studio code as a code editor.

Step 1. Install ionic
The first step is we need to install ionic tooling. Run the below command to install ionic CLI.

  • native-run: Used to run native binaries on devices and simulators/emulators.
  • cordova-res: Used to generate icons and splash screens for the native app.

npm install -g @ionic/cli native-run cordova-res

Step 2. Create an Application
Run the below command to create an ionic application. We will create a calculator for this article’s explanation. Check out the below screen prints for command execution.

ionic start calculator

Step 3. Write an Application Code
home.page.html
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Calculator
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Blank</ion-title>
    </ion-toolbar>
  </ion-header>

  <div id="container">
    <div class="jumbotron col-sm-4 p-2 m-0 bg-inverse mx-auto" style="border: 1px solid lightgray; border-radius: 2%;">
      <label style="font-weight: bolder;">Input</label>
      <div class="input-group input-group-sm col-sm-12 m-0 p-0">
        <div class="col-sm-12 form-control text-lg-right" type="text">{{input}}</div>
      </div>
      <label style="font-weight: bolder;">Result</label>
      <div class="input-group input-group-sm col-sm-12 m-0 p-0">
        <div class="form-control text-sm-right" type="text">{{result}}</div>
      </div>
      <div class="col-sm-12 p-1 m-0">
        <button class="btn btn-info col-sm-6" type="button" (click)="allClear()">C</button>
        <button class="btn btn-warning col-sm-3" type="button" (click)="clear()">x</button>
        <button class="btn btn-secondary col-sm-3" type="button" (click)="pressOperator('/')">/</button>
      </div>
      <div class="col-sm-12 p-1 m-0">
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('7')">7</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('8')">8</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('9')">9</button>
        <button class="btn btn-secondary col-sm-3 p-1" type="button" (click)="pressOperator('*')">X</button>
      </div>
      <div class="col-sm-12 p-1 m-0">
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('4')">4</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('5')">5</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('6')">6</button>
        <button class="btn btn-secondary col-sm-3 p-1" type="button" (click)="pressOperator('-')">-</button>
      </div>
      <div class="col-sm-12 p-1 m-0">
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('1')">1</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('2')">2</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('3')">3</button>
        <button class="btn btn-secondary col-sm-3 p-1" type="button" (click)="pressOperator('+')">+</button>
      </div>
      <div class="col-sm-12 p-1 m-0">
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('.')">.</button>
        <button class="btn btn-outline-secondary col-sm-3 p-1" type="button" (click)="clickNum('0')">0</button>
        <button class="btn btn-success col-sm-6 p-1" type="button" (click)="getAnswer()">=</button>
      </div>
    </div>
  </div>
</ion-content>


home.page.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  input: string = '';
  result: string = '';

  clickNum(num: string) {
    // Do Not Allow . more than once
    if (num == ".") {
      if (this.input != "") {
        const lastNum = this.getLastOperand();
        console.log(lastNum.lastIndexOf("."));
        if (lastNum.lastIndexOf(".") >= 0) return;
      }
    }

    // Do Not Allow 0 at beginning.
    // Javascript will throw Octal literals are not allowed in strict mode.
    if (num == "0") {
      if (this.input == "") {
        return;
      }
      const PrevKey = this.input[this.input.length - 1];
      if (PrevKey === '/' || PrevKey === '*' || PrevKey === '-' || PrevKey === '+') {
        return;
      }
    }

    this.input = this.input + num;
    this.calcAnswer();
  }

  getLastOperand() {
    let pos: number;
    console.log(this.input);
    pos = this.input.toString().lastIndexOf("+");
    if (this.input.toString().lastIndexOf("-") > pos) pos = this.input.lastIndexOf("-");
    if (this.input.toString().lastIndexOf("*") > pos) pos = this.input.lastIndexOf("*");
    if (this.input.toString().lastIndexOf("/") > pos) pos = this.input.lastIndexOf("/");
    console.log('Last ' + this.input.substr(pos + 1));
    return this.input.substr(pos + 1);
  }

  pressOperator(op: string) {
    // Do not allow operators more than once
    const lastKey = this.input[this.input.length - 1];
    if (lastKey === '/' || lastKey === '*' || lastKey === '-' || lastKey === '+') {
      return;
    }

    this.input = this.input + op;
    this.calcAnswer();
  }

  clear() {
    if (this.input != "") {
      this.input = this.input.substr(0, this.input.length - 1);
    }
  }

  allClear() {
    this.result = '';
    this.input = '';
  }

  calcAnswer() {
    let formula = this.input;

    let lastKey = formula[formula.length - 1];

    if (lastKey === '.') {
      formula = formula.substr(0, formula.length - 1);
    }

    lastKey = formula[formula.length - 1];

    if (lastKey === '/' || lastKey === '*' || lastKey === '-' || lastKey === '+' || lastKey === '.') {
      formula = formula.substr(0, formula.length - 1);
    }

    console.log("Formula " + formula);
    this.result = eval(formula);
  }

  getAnswer() {
    this.calcAnswer();
    this.input = this.result;
    if (this.input == "0") this.input = "";
  }
}

home.page.scss
#container {
  text-align: center;

  position: absolute;
  left: 0;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

#container strong {
  font-size: 20px;
  line-height: 26px;
}

#container p {
  font-size: 16px;
  line-height: 22px;

  color: #8c8c8c;

  margin: 0;
}

#container a {
  text-decoration: none;
}

.col-sm-3 {
  flex: 0 0 auto;
  width: 23%;
  margin: 1%;
}

@media (min-width: 576px) {
  .col-sm-3 {
      flex: 0 0 auto;
      width: 23%;
      margin: 1%;
  }
}

.form-control{
  min-height: 30px;
}


Step 4. Add required packages
We can add third-party packages as per requirements. Here for this demo, I have used Bootstrap to make the UI smooth. Run the below command to install the Bootstrap.

Move to the application path using the below command.
cd calculator
npm i bootstrap bootstrap-icons
ng add @ng-bootstrap/ng-bootstrap

Import bootstrap to styles.scss file located at the root level.

Step 5. Run the Application with Browser
Run the below command to execute the application in a browser.
ionic serve


You can examine the folder structure and the created/generated www folder as soon as the application launches in the browser. All of the JavaScript code generated for the application is stored in the www folder. This is a www, similar to the dist folder in an Angular application. For an example, view the screen print below.


Step 6. Install the Android SDK
Once all application runs on the browser, we now need to run the same application on mobile devices like iOS or Android. For this article demonstration, I’m using an Android device. So I’ll generate the .apk file.

Now, let’s see how we can generate the APK file.

Let’s first run the below command in the terminal of the application path to generate apk.
ionic capacitor build android

If Android Studio is installed it will show a response like the below screen print, otherwise, you need to install Android Studio.


On My machine, I have already Android Studio installed. But you can get Android Studio from the mentioned path and get installed like the below screen print


Android Studio SDK path. Sometimes it takes time to download all required packages and it throws errors like the below screen print.

You can just close the error popup and close the project. It will start downloading pending packages and once all required packages are installed it will show a screen like below with the SDK path.


Step 7. Build the APK
Once the Android studio setup is done we can build apk file. To build apk file go to android studio -> build -> Build App Bundle(s) / APK(s) -> Build APK(s)

While building apk it will show the status like the below screen print.

Once APK generated you can click on locate and see the apk file.

Let’s install the APK file on an Android device.

Installed calculator application then let’s run application on the Android mobile device.




AngularJS Hosting Europe - HostForLIFE :: Combining jQuery Select2 with AngularJS for Dropdown Modifications

clock September 6, 2024 09:21 by author Peter

In contemporary web development, integrating many libraries and frameworks is frequently necessary to provide a seamless user experience. Combining AngularJS with jQuery Select2 to improve dropdown menus is one typical use case. This post looks at how to properly handle dropdown changes and synchronize AngularJS models with Select2.


Overview
For creating dynamic online applications, AngularJS is a strong framework. On the other hand, jQuery Select2 is a well-liked library that offers improved dropdown menu features like searching, tagging, and more. By combining these technologies, a strong user interface with cutting-edge features can be produced.

Setting up the Environment
First, ensure you have included the necessary libraries in your project.

  • AngularJS: For data binding and MVC functionality.
  • jQuery: Required by Select2 for DOM manipulation.

Select2: For advanced dropdown functionality
code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />

<div class="col-md-3 mt-3">
    <label class="text-muted font-weight-bold">demoDis*</label>
    <select id="txtID" name="txtID" class="form-control select2" ng-model="Refundval" ng-options="lobjdata.Value as lobjdata.Name for lobjdata in ListMaster">
        <option value="" disabled selected hidden>Select</option>
    </select>
    <input type="hidden" id="hdRefundID" ng-model="hdRefundID" value="" />
</div>

app.controller('MyController', function($scope) {
    // Function to initialize Select2 and handle changes
    $scope.demoBan = function() {
        debugger;
        var Reta = JSON.parse(localStorage.getItem("Get"));
        console.log("RetailerId", RetailerId);
        $scope.ListMaster = Reta;
        angular.element(document).ready(function() {
            // Initialize Select2
            $('#txtID').select2();

            $('#txtID').on('change.select2', function() {
                var selectedValue = $(this).val();
                var selectedText = $('#txtID option:selected').text(); // Get the text of the selected option
                $scope.$applyAsync(function() {
                    // Update AngularJS model
                    $scope.Id = selectedValue;
                    $scope.Text = selectedText.trim(); // Store the text of the selected option
                    console.log("Selected Value:", selectedValue);
                    console.log("Selected Text:", $scope.Text);
                });
            });
        });
    };
});


Explanation

  • Initialization: Use angular. element(document).ready() to ensure that the DOM is fully loaded before initializing Select2.
  • Handling Changes: Bind to Select2’s change event to capture user selections. Use $scope.$applyAsync() to update AngularJS models and ensure the changes are reflected in the view.

Conclusion
Integrating AngularJS with Select2 can significantly enhance the user experience by combining Angular’s data binding capabilities with Select2’s advanced dropdown features. By following the steps outlined, you can effectively synchronize models between AngularJS and Select2, providing a seamless interaction for your users.



AngularJS Hosting Europe - HostForLIFE :: Various Methods in Angular for Redirecting and Retrieving ID Parameters

clock September 3, 2024 08:03 by author Peter

Angular is a potent front-end framework that offers numerous methods for data passing, including ID parameters, and component navigation. Whether you're developing a sophisticated enterprise application or a single-page application (SPA), handling routing correctly requires knowing how to extract parameters and redirect users.


1. Using Basic Navigation with the RouterLink Directive

In Angular, the easiest way to move between components is with the RouterLink directive. It assists in creating URLs with dynamic parameters and is utilized directly in templates.

<a [routerLink]="['/employee', employee.id]">View Details</a>

The employee.id is appended to the /employee route, creating a dynamic URL like /employee/123. This is a convenient way to navigate when the route parameters are known within the template.

2. Programmatic Navigation with the Router
For more complex scenarios, such as navigation that depends on some business logic or conditional operations, Angular’s Router service can be used for programmatic navigation.
import { Router } from '@angular/router';
constructor(private router: Router) {}
viewEmployeeDetails(employeeId: number) {
  this.router.navigate(['/employee', employeeId]);
}


navigate() method takes an array where the first element is the route path, and the subsequent elements are the route parameters.

3. Retrieving Parameters Using ActivatedRoute
Once you’ve navigated to a route that includes parameters, you'll often need to retrieve those parameters in the component. Angular provides the ActivatedRoute service for this purpose.
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
  const employeeId = this.route.snapshot.paramMap.get('id');
  console.log('Employee ID:', employeeId);
}

snapshot.paramMap.get('id') retrieves the id parameter from the route. This is a synchronous method, meaning it grabs the parameter value only at the moment of the component's creation.

4. Using Observables for Dynamic Parameter Retrieval

While snapshot is useful for simple use cases, Angular applications often require handling route changes dynamically without destroying and recreating components. This is where paramMap as an Observable comes into play.
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
  this.route.paramMap.subscribe(params => {
    const employeeId = params.get('id');
    console.log('Employee ID:', employeeId);
  });
}


paramMap.subscribe() ensures that every time the id parameter changes, the new value is logged or processed accordingly. This is ideal for components that need to respond to route changes dynamically.

5. Combining Query Parameters with Navigation
Sometimes, you may want to navigate to a route and include additional information via query parameters. Angular’s Router service allows combining both route parameters and query parameters.
this.router.navigate(['/employee', employeeId], { queryParams: { ref: 'dashboard' } });

navigation directs to /employee/123?ref=dashboard, where 123 is the route parameter, and ref=dashboard is a query parameter.

If you want to retrieve the query parameters in the component
this.route.queryParams.subscribe(params => {
  const ref = params['ref'];
  console.log('Referred from:', ref);
});

6. Redirection after Form Submission
Another common use case is redirecting the user after a form submission or some action completion.
onSubmit() {
  // Assuming form submission is successful
  this.router.navigate(['/employee', newEmployeeId]);
}


7. Handling Complex Redirections with Guards
Angular also supports complex redirection scenarios using route guards. Guards can intercept navigation and redirect users based on certain conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}
  canActivate(): boolean {
    if (isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}


if the is logged in () function returns false, the user is redirected to the /login route, preventing unauthorized access.

Conclusion
Navigating between routes and handling parameters in Angular is a fundamental aspect of building dynamic and user-friendly applications. Whether you use the simple RouterLink, programmatic navigation, or complex redirection logic, Angular provides the tools to handle a wide range of routing scenarios efficiently.

Happy Coding!



AngularJS Hosting Europe - HostForLIFE :: Knowing Angular vs. React

clock August 19, 2024 10:08 by author Peter

React and Angular are two of the most widely used front-end frameworks for creating contemporary online apps. Both are supported by sizable groups and have distinct advantages, yet they serve varying needs and tastes. We'll go over the main distinctions between Angular and React in this post to assist you in choosing the right framework for your project.

 

Overview

  1. React
    • Developed by: Facebook
    • Initial Release: 2013
    • Type: JavaScript library for building user interfaces, primarily focused on rendering UI components.
    • Learning Curve: Moderate
    • Main Concept: React is centered around components and follows a unidirectional data flow.
  2. Angular
    • Developed by: Google
    • Initial Release: 2016 (as Angular 2, the complete rewrite of AngularJS)
    • Type: Full-fledged framework for building web applications.
    • Learning Curve: Steep
    • Main Concept: Angular is an opinionated framework that provides a comprehensive solution for building large-scale applications, including built-in features like routing, state management, and HTTP services.

Architecture

  1. React
    • Component-Based: React is all about components. Each piece of UI is a component that can manage its state and be reused throughout the application.
    • Virtual DOM: React uses a virtual DOM to optimize rendering performance. When the state of a component changes, React updates the virtual DOM and then efficiently updates the real DOM.
    • Flexibility: React offers flexibility by allowing developers to choose their own libraries for routing, state management, and other needs. This makes React a "view library" rather than a full-fledged framework.
  2. Angular
    • MVC Architecture: Angular follows the Model-View-Controller (MVC) pattern, which helps in separating the concerns of data (Model), UI (View), and logic (Controller).
    • Real DOM: Unlike React, Angular directly interacts with the real DOM, which can impact performance in complex applications. However, Angular mitigates this with its change detection mechanism.
    • Built-In Features: Angular comes with a range of built-in features like form validation, HTTP client, routing, and RxJS for reactive programming. This makes Angular a complete solution for building applications without relying on external libraries.

Performance

  1. React
    • Virtual DOM: React’s virtual DOM significantly improves performance by minimizing the number of direct manipulations to the real DOM.
    • Component Reusability: React’s component-based architecture promotes reusability, which can lead to better performance in large applications.
    • Bundle Size: React itself is relatively lightweight, but depending on the additional libraries you use, the bundle size can grow.
  2. Angular
    • Change Detection: Angular’s change detection mechanism can sometimes lead to performance bottlenecks in large applications, but it also provides tools like OnPush strategy and NgZone to optimize performance.
    • Ahead-of-Time (AOT) Compilation: Angular’s AOT compilation improves performance by compiling the application during the build process, reducing the load time.
    • Built-In Features: While Angular’s rich feature set can impact performance, the framework’s ability to optimize these features mitigates the impact.

Learning Curve

  1. React
    • JSX: React uses JSX, a syntax extension that allows you to write HTML within JavaScript. While some developers find JSX intuitive, others might find it challenging initially.
    • Flexibility: React’s flexibility means you need to learn how to integrate and use various libraries for routing, state management, etc., which can be both an advantage and a challenge.
    • Documentation and Community: React has extensive documentation and a large community, making it easier to find resources, tutorials, and third-party libraries.
  2. Angular
    • Steep Learning Curve: Angular has a steeper learning curve due to its complexity and the number of built-in features you need to understand.
    • TypeScript: Angular is built with TypeScript, a statically typed superset of JavaScript. While this adds benefits like better tooling and error checking, it also requires learning TypeScript if you’re not already familiar with it.
    • Comprehensive Framework: Angular’s opinionated nature means that once you learn the Angular way of doing things, you have a powerful set of tools at your disposal.

Ecosystem and Community

  1. React
    • Ecosystem: React has a rich ecosystem with numerous libraries for state management (Redux, MobX), routing (React Router), and more. The flexibility to choose different tools gives developers more control over their stack.
    • Community: React has a large and active community, contributing to a vast array of plugins, tools, and resources.
  2. Angular
    • Ecosystem: Angular has a more integrated ecosystem. Many features that require third-party libraries in React are built into Angular, such as routing, HTTP services, and form handling.
    • Community: Angular also has a large community, but it is more centralized around the official Angular resources, documentation, and Google-backed initiatives.

Use Cases
 

React

  1. When to Use React
    • You need flexibility in choosing libraries and tools.
    • You prefer a simple, component-based architecture.
    • You are building a project where performance and simplicity are key.
  2. Popular Use Cases
    • Single-page applications (SPAs)
    • Static sites with dynamic components
    • Dashboards and data visualization tools

Angular

  1. When to Use Angular
    • You are building a large-scale, enterprise-level application.
    • You need a framework with a comprehensive set of tools and built-in features.
    • You prefer an opinionated framework that guides architectural decisions.
  2. Popular Use Cases
    • Complex, enterprise-level applications
    • Applications requiring robust form handling and validation
    • Real-time applications with complex state management

Conclusion
The skills of your team and the needs of your project will determine which of React and Angular is best. React is an excellent option for projects where you want more control over the architecture because of its simplicity and versatility. In contrast, Angular offers a feature-rich, opinionated framework right out of the box, making it perfect for enterprise-level apps. Both Angular and React are effective front-end development tools, and knowing the advantages and disadvantages of each will help you choose wisely for your upcoming project.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in