Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: How to Create Unit Test Cases with Mocking Service in Angular?

clock February 26, 2024 06:42 by author Peter

Writing unit tests with mocking services is a typical Angular approach for isolating the component under test from external dependencies like services. This allows you to test the component in isolation while focusing on its behavior. Here's a step-by-step approach for creating a unit test case using a mocked service in Angular using Jasmine and TestBed:

Assume you have a component named MyComponent that depends on a service called MyService. We'll build a dummy for MyService and use it during the test.
Create a component (my.component.ts).

// my.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-my',
  template: '<div>{{ data }}</div>',
})
export class MyComponent implements OnInit {
  data: string;

  constructor(private myService: MyService) {}

  ngOnInit(): void {
    this.data = this.myService.getData();
  }
}

Create the Service (my.service.ts)

// my.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MyService {
  getData(): string {
    return 'Hello from MyService!';
  }
}


Create the Unit Test (my.component.spec.ts)
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MyService } from './my.service';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let myServiceMock: jasmine.SpyObj<MyService>;

  beforeEach(() => {
    // Create a spy object for the service
    myServiceMock = jasmine.createSpyObj('MyService', ['getData']);

    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [{ provide: MyService, useValue: myServiceMock }],
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should set data from service', () => {
    // Configure the spy behavior
    myServiceMock.getData.and.returnValue('Mocked data');

    // Trigger ngOnInit
    component.ngOnInit();

    // Check if the data property has the expected value
    expect(component.data).toBe('Mocked data');
  });
});


In this example, we use the jasmine.createSpyObj function to generate a spy object for the MyService class. We then use the TestBed.configureTestingModule function to incorporate this dummy service into the testing module. The beforeEach function configures the testing module, creates a component fixture, and creates a component instance.

In the second test, we configure the spy to return a specified value when the getData function is called, and then we execute the component's ngOnInit method to verify its behavior. This is a basic example, and you may need to modify it for your own use case. Remember that Angular testing can include more advanced situations like testing asynchronous code, working with forms, and interacting with the DOM.



AngularJS Hosting Europe - HostForLIFE :: Get Browser Type and Version Using Angular and Bootstrap

clock February 20, 2024 06:04 by author Peter

This article explains how to retrieve the browser name and version from the Angular application. In certain cases, you may also need to obtain the browser name in Angular, depending on your requirements. If the Angular application is open on Internet Explorer Legacy, Edge, Firefox, Chrome, Safari, Opera, or another browser, we can quickly identify it. This article walks us through the process of adding a reusable method to an Angular application and demonstrates how to quickly identify the browser and version.


Note: Before beginning this session, please read my earlier essay (linked below) about Angular applications.

D:\EmployeeManagement\CallWebAPIAngular> ng g s services/detect-browser

Then you can service and its related files are shown below
PS D:\EmployeeManagement\CallWebAPIAngular> ng g s services/detect-browser
CREATE src/app/services/detect-browser.service.spec.ts (393 bytes)
CREATE src/app/services/detect-browser.service.ts (142 bytes)


Step 2. Configure browser name with version detection method
After creating the DetectBrowserService, add the getBrowserNameAndVersion() method to return an object with name and version keys. This method will fetch the User-Agent strings on the browser in which the Angular application is loaded.

Open the ~app\services\detect-browser.service.ts file and add as shown below.
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class DetectBrowserService {
  constructor() { }
  getBrowserNameAndVersion() {
    var ua = navigator.userAgent,
        tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'IE', version: (tem[1] || '') };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bEdg\/(\d+)/);
        if (tem != null) {
            return { name: 'Edge(Chromium)', version: tem[1] };
        }
        tem = ua.match(/\bOPR\/(\d+)/);
        if (tem != null) {
            return { name: 'Opera', version: tem[1] };
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }
    return {
      name: M[0],
      version: M[1]
    };
  }
}


Here, we detect the name and version of the browser by creating a new service with a common method. The getBrowserNameAndVersion method returns an object with name and version keys. This method is fetching the User-Agent string that provides the browser information.

Step 3. Detect browser name with version
Now, we will import the DetectBrowserService in the AppComponent‘s constructor function. The service instance method named getBrowserNameAndVersion() will assign the name and version object to the browserNameAndVersion variable.

Open the app.component.ts file and add as shown below

import { Component } from '@angular/core';
import { DetectBrowserService } from './services/detect-browser.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Display Browser Name & Version';

  public requiredVersion = 98;
  public isBrowserOutdated: boolean | undefined;
  public browserVersion = '';
  browserNameAndVersion: any;

  constructor(
    detectBrowserService: DetectBrowserService
  ) {
    this.browserNameAndVersion = detectBrowserService.getBrowserNameAndVersion();
    this.browserVersion = this.browserNameAndVersion.version;
    if (parseFloat(this.browserNameAndVersion.version) < this.requiredVersion) {
      this.isBrowserOutdated = true;
    }
  }
}

Here we configure for displaying browser name and version along with browser up-to-date or not.

this.browserNameAndVersion = detectBrowserService.getBrowserNameAndVersion();
this.browserVersion = this.browserNameAndVersion.version;
if (parseFloat(this.browserNameAndVersion.version) < this.requiredVersion) {
  this.isBrowserOutdated = true;
}


Step 4. HTML template to show browser name with version
Update the HTML template of AppComponent to display the browser name and version. Open the app.component.html file and update it as shown below:

<div class="card bg-danger text-white">
  <div class="card-body text-center">
    <h1>{{ title }}</h1>
  </div>
  <table class="table table-striped mt-5">
    <thead>
    </thead>
    <tbody>
      <tr>
        <td><h4>Browser Name: {{ browserNameAndVersion.name | titlecase }}</h4></td>
        <td><h4>Current Browser Version: {{ browserNameAndVersion.version | titlecase }}</h4></td>
        <td><h4>Required Version: {{ requiredVersion }}</h4></td>
      </tr>
    </tbody>
  </table>
</div>

<div class="toast show" style="position: fixed; top: 60%; left: 50%; width: 30em; height: 17em; margin-top: -9em; margin-left: -15em; border: 1px solid #ccc; background-color: #f3f3f3; color: red; font-weight: 900; font-size: larger;">
  <div class="toast-header">
    Angular Detect Browser Name and Version
    <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
  </div>
  <div class="toast-body">
    <div class="base-block" *ngIf="isBrowserOutdated">
      <h1>Oops</h1>
      <h3>Browser is outdated</h3>
      <h5>
        Your {{ browserNameAndVersion.name }} browser is outdated ({{ browserNameAndVersion.version }}) as less than required Version
        ({{ requiredVersion }}) and no longer supported, please update your browser.
      </h5>
    </div>

    <div class="base-block" *ngIf="!isBrowserOutdated">
      <h1>Cheers!</h1>
      <h3>Browser is up to date</h3>
      <h5>
        Your {{ browserNameAndVersion.name }} browser is updated ({{ browserNameAndVersion.version }}).
      </h5>
    </div>
  </div>
</div>


Use the interpolation to display the browser name and version with the help of the interpolation. An Interpolation is defined using the double curly braces that permit the user to bind a value to a UI element. Also, we will use the angular pipe to transform the value in the title case.

<td>
  <h4>Browser Name: {{ browserNameAndVersion.name | titlecase }}</h4>
</td>
<td>
  <h4>Current Browser Version: {{ browserNameAndVersion.version | titlecase }}</h4>
</td>
<td>
  <h4>Required Version: {{ requiredVersion }}</h4>
</td>

Check browser is up-to-date or not based on some condition using the *ngIf directive.
<div class="toast-body">
  <div class="base-block" *ngIf="isBrowserOutdated">
    <h1>Oops</h1>
    <h3>Browser is outdated</h3>
    <h5>
      Your {{ browserNameAndVersion.name }} browser is outdated ({{ browserNameAndVersion.version }}) as less than required Version
      ({{ requiredVersion }}) and no longer supported, please update your browser.
    </h5>
  </div>

  <div class="base-block" *ngIf="!isBrowserOutdated">
    <h1>Cheers!</h1>
    <h3>Browser is up to date</h3>
    <h5>
      Your {{ browserNameAndVersion.name }} browser is updated ({{ browserNameAndVersion.version }}).
    </h5>
  </div>
</div>


Step 5. Add Bootstrap to make the page responsive
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Title Service Example</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>


Output

Finally, run the application by executing the ng serve command in the terminal window. It opens the application at the following URL: http://localhost:4200/
Checking Chrome Browser is up to date i.e. based required Version

Checking whether Chrome Browser is up to date or not i.e. based on the Required Version

Checking whether another Browser is up to date or not i.e. based on the Required Version

Why is it necessary to set up the browser detection procedure?
To let users know that their current browser or version isn't compatible with correctly loading the application, we need to identify the name and version of their browser. They can then use the newest browsers that are out there. Modern Javascript and CSS principles are supported by a wide range of web browsers accessible today, all of which are completely compatible with the most recent version of WebKit. In this situation, we must identify the browser's name and version in order to let users know that their current browser or a different one isn't compatible with correctly loading the program and that they can upgrade to the newest version.



AngularJS Hosting Europe - HostForLIFE :: Angular 17 New Features

clock February 16, 2024 08:10 by author Peter

As part of its new movement, Angular 17 provides Signals and Standalone Components. You can anticipate an enhanced Angular Renaissance with Angular 17. It features enhanced support for Server-Side Rendering (SSR), a new control flow syntax, and greater support for lazy loading of page components. Furthermore, the CLI now uses ESBuild, which greatly improves the build procedure.

Integrated Control Flow Automated Transfer
The @angular/core package contains a schematic that you can use to automatically convert your code to the new control flow syntax.

ng g @angular/core:control-flow

Technical Updates in Angular

New looping syntax

  • If-then-else
  • Switch
  • Block directives
  • Deferred rendering
  • SSR and SSG
  • New build system
  • Improved debugging for dependency injection

New Looping Syntax
You can see a live example of the new looping capability in the Angular playground. In this example, we loop over an array of to-do items.

@for (todo of todos; track $index) {
    ...
}


That’s pretty succinct. We expose the todo variable for each element of todos, and we “track” the built-in $index field. The $index variable will show the automatically generated row number for the element (there are other implicit variables like $first, $odd, and $count). You can also use a field on the elements you want to track.
@for (todo of todos; track todo.id) {...}


In this new syntax, the track variable is required, by design. In previous incarnations, the tracking variable was optional, which led to performance degradation. The tracking key on a loop enables the rendering engine to optimize the list display and know what has changed.

If-then-else

@if (todo.done) {
    <s>{{ todo.text }}</s>
} @else {
    <span>{{ todo.text }}</span>
}


Being able to provide the content for @else directly is a major simplification compared to the else clause of the legacy *ngIf alternative. The current control flow also makes it trivial to have @else if, which historically has been impossible.

Switch

Angular’s new switch syntax applies typical JavaScript syntax to templates.

@switch (condition) {

  @case (caseA) {
    <span>Case A.</span>
  }

  @case (caseB) {
    <span>Case B.</span>
  }

  @default {
    <span>Default case.</span>
  }

}


The new control flow enables significantly better type-narrowing in the individual branches in @switch which is not possible in *ngSwitch.

Deferred Rendering
Angular now supports deferred rendering via the block syntax. This gives you a simple and powerful mechanism for defining ways to tell the browser what to display along with instructions for doing it in a non-linear way. The Angular 17 tutorial has some good examples of using @defer.

Here's an example of the simplest @defer.
@defer {
    <span>My deferred content</span>
}


This tells the browser to render the rest of the page first, and then the deferred content. It's a very simple syntax for the times when you want to avoid front-loading everything.

You can also provide @placeholder and @loading blocks.
@defer {
    <span>My deferred content</span>
}

@placeholder {
    <span>Placeholder content</span>
}

@loading {
    <span>Loading deferred content...</span>
}


Placeholder and loading both provide a static layout for the coming content, @placeholder first, then @loading.

Several different strategies are supported by @defer out of the box, like viewport (when the user scrolls it into view), idle (browser is idle), interaction (user interacts with the element), and hover (pointer hovers on the element). Here's an example using hover.
@defer (on hover) {
    <span>My hover content</span>
}

There’s even a @defer(when <expression>) that takes a promise, so you can really defer on any conceivable situation. All in all, the new @defer mechanism is impressive. Deferred rendering is usually persnickety and really interferes with the flow of a developer's thoughts and the resulting code. This latest version of Angular makes it easy.

Note that @defer is still a developer preview in Angular 17, but is considered production-ready.

New Build System

Angular has joined the Vite movement, and Angular 17 uses Vite with Esbuild as its build engine. This was a required change for underpinning the new SSR system. For developers, the main impact is that it's faster, including for serving and updating in dev mode.

Block Directives
@for, @if, and @switch are new “block” directives. They allow us to inject chunks of markup into the template using JavaScript syntax. These new directives replace previous approaches like *ngIf. You can still use *ngIf and other older syntax, and an automated command in the CLI lets you change over to the block syntax.

ng generate @angular/core:control-flow




AngularJS Hosting Europe - HostForLIFE :: Configuring Micro Frontend with the Most Recent Angular Version

clock February 12, 2024 06:39 by author Peter

A micro frontend is what?
A frontend application is divided into smaller, independent, modular components that may be built, deployed, and maintained independently in a micro frontend architecture. Since each component (micro frontend) concentrates on a particular area of the application, it is easier to scale and maintain, particularly in complicated and large-scale projects.


This architectural approach divides the user interface into more manageable, autonomous, and independently deployable components in order to construct web applications. Each of these parts—often called micro frontends—represents a particular application feature, page, or capability.

A web application is developed and implemented as a single unit in a classic monolithic design. Conversely, micro frontends disassemble the frontend into smaller components that can be independently developed, tested, and deployed. A distinct release cycle, technology stack, and development team may be assigned to every micro frontend.

Module Federation addresses several challenges in this context:

Decentralized Development

  • Challenge: Micro frontends need to be developed independently by different teams.
  • Solution: Module Federation allows each micro frontend to have its own codebase, dependencies, and build process, enabling decentralized development.

Dynamic Module Loading

  • Challenge: Loading all modules upfront can lead to slow initial page loads.
  • Solution: Module Federation supports dynamic module loading, where modules are loaded on-demand as users interact with the application. This optimizes the initial loading time.

Loose Coupling

  • Challenge: Micro frontends should communicate without tightly coupling their codebases.
  • Solution: Module Federation ensures loose coupling by defining clear module boundaries and communication interfaces. Micro frontends can interact via APIs or messaging without direct dependencies on internal details.

Versioning and Compatibility

  • Challenge: Coordinating versions of shared dependencies is complex.
  • Solution: Module Federation provides a mechanism for sharing and managing dependencies. Each micro frontend specifies its dependencies, and the build system ensures compatibility.

Loose Coupling

  • Challenge: Micro frontends should communicate without tightly coupling their codebases.
  • Solution: Module Federation ensures loose coupling by defining clear module boundaries and communication interfaces. Micro frontends can interact via APIs or messaging without direct dependencies on internal details.
Seamless Integration
  • Challenge: Micro frontends must seamlessly integrate when necessary.
  • Solution: Module Federation allows for shared components or functionality, ensuring that micro frontends can work together seamlessly when needed.
Optimized Code Splitting
  • Challenge: Efficiently splitting code into smaller, manageable chunks is crucial for performance.
  • Solution: Module Federation optimizes code splitting by intelligently sharing common code among micro frontends while preserving their autonomy.
In technical terms, Module Federation facilitates a modular, dynamic, and loosely coupled architecture, providing a scalable solution for large and complex web applications built with a micro frontend approach.

Getting started

Structuring a system that operates on a micro frontend architecture can be broken down into 2 main parts.

The host application
  • This is also referred to as 'main app' or 'shell app'. It is the application that will consume the micro frontend. You can consider it as the application that the user will use and for it to be fully working, it needs to use the micro services.
  • The microservice
  • Micro frontends are independent, self-contained applications or modules that contribute to the overall user interface.Each micro frontend is developed and maintained by a separate team, allowing for decentralized development. Micro frontends can be features, sections, or components of the larger application. They communicate with the host app and other micro frontends using defined APIs or messaging mechanisms. Micro frontends can be developed using different technologies, frameworks, or even languages, providing flexibility to development teams.
Creating the host app
Generate a new angular project called host app using the command below
ng new host-app --standalone false

Angular will ask for your preferred style sheet format and if you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering). For the latter, I selected "No". The answer to these two questions are up to you.

Once your project is generated, move into the host app. Below is the command in the terminal to do so:
cd host-app

Then, run the following command to all module federation in your host app:
ng add @angular-architects/module-federation
  • You will be asked if you want to proceed. Obviously, say "Yes" !!
  • You will also be asked your project name. You can enter the same name as your angular project, that is, "host-app".
  • You will have to choose on which port to run the project. I chose "5000".
  • Once the command is completed, the host-app is 'micro frontend' ready.

NOTE

You will notice that 2 new files have been created.
The first one is webpack.config.ts and the second one is webpack.prod.config.ts.

The webpack.config.ts and webpack.prod.config.ts files are configuration files for Webpack, a popular JavaScript module bundler. These files define how Webpack should process, bundle, and output your project's assets, such as JavaScript files, stylesheets, and images.

The file contains the configuration for development (or sometimes referred to as the "dev" configuration). The development configuration is optimized for speed and provides additional tools for debugging.

The second one contains the same configuration but for production.

Creating a micro frontend
Generate a new angular project called host app using the command below
ng new mfe-one --standalone false

Angular will ask for your preferred style sheet format and if you want to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering). Here again, I selected 'No'. The answers to these two questions will depend on you.

Once your project is generated, move into the host app
cd mfe-one

Then, run the following command to all module federation in your host app:
ng add @angular-architects/module-federation

You will be asked the same questions as for the host app. Answer the same way except for the port. All ports to be used should be unique and different be it the host app and all the micro frontends. For our case, we will use port 7000.

In webpack.config.js, you will see a comment 'For remotes'.
It is under this that you will configure how the micro frontend will be exposed.
Following this comment, the next 4-5 commented lines are an example already given to you when you install module federation.
To get started, uncomment the lines starting with: 'name', 'filename' and 'exposes'.
The property 'name' can stay the same.
The property 'filename' must remain 'remoteEntry.js'.

The property 'exposes' should contain an array of a list of how to expose the micro frontend to the host application.

For our micro frontend, we do the following:
// For remotes (please adjust)
   name: "mfeOne",
   filename: "remoteEntry.js",
   exposes: {
       './my-first-mfe': './/src/app/app.module.ts',
  },

In the app-routing.module.ts file, modify the routes constant to the following:
const routes: Routes = [
{
path: '',
component: AppComponent,
pathMatch: 'full',
}
];


Also, change the imports list to the following:
imports: [RouterModule.forChild(routes)],

In the app.component.ts, update the 'selector name' to the following
selector: 'app-root:not(p)'

Also, change the name of the export class from 'AppComponent' to something more unique. We have changed ours to 'MyFirstMfeAppComponent'. This will result in making some updates in the app.module.ts, where the App Component is imported and needs to be changed to the new name.

NOTE: The first part of the key value pair in the 'exposes' array is user defined. You get to choose it, but its value needs to be a module. It can be the module file for a component or the app module component like in our case.

These steps are all the steps required to create a micro frontend. Now we need to connect the micro frontend and the host app.
Connecting the micro frontend and the host app

All of the following steps will be done in the host app.
In the assets folder, create a file and call it 'mf.manifest.json'. This file will contain an array of all the micro frontends that the host app will consume. Remember to add all your micro frontend here. Below is ours:
{
   "my-first-mfe": "http://localhost:3000/remoteEntry.js"
}

In the src folder, create a 'decl.d.ts' file.
In this file, declare the path of the module of the micro frontend.
The path is in the form <name of the micro frontend project>/<name in the 'exposes' part of the webpack config in the micro frontend project>

Ours will look like below:
declare 'mfe-one/my-first-mfe'

Modify the main.ts file to add the following code:
import { loadManifest } from '@angular-architects/module-federation';

import('./bootstrap')
.catch(err => console.error(err));

loadManifest("/assets/mf.manifest.json")
.catch(err => console.error(err))
.then(_ => import('./bootstrap'))
.catch(err => console.error(err));


In the app-routing.module.ts, add the path for the micro frontend in the 'routes' list. Do not forget to add the following import:
import { loadRemoteModule } from '@angular-architects/module-federation';

The 'routes' list should look like below:
const routes: Routes = [
{
path: 'my-first-mfe',
loadChildren: () =>
 loadRemoteModule(
   {
   type: 'module',
   remoteEntry: 'http://localhost:7000/remoteEntry.js',
   exposedModule: './my-first-mfe',
 }
 ).then((m) => m.AppModule),
}
];

The 'path' is the url path to access the page from the micro frontend. For example here, http://localhost:5000/my-first-mfe. The value of the path is up to you.
The 'remoteEntry' is the path of the remoteEntry.js file for your micro frontend. Typically, it is the url of your micro frontend,i.e. Localhost:<<port you chose when add module federation in your micro frontend>>/remoteEntry.js.

The 'exposedModule' is the one defined in the webpack.config.js of your micro frontend.

In the webpack.config.js file, uncomment the lines after the comment (For hosts (please adjust)). In 'remotes', we need to add the url to the remoteEntry.js files for the micro frontend. Below is how to do it for our example:
remotes: {
       "mfeOne": "http://localhost:7000/remoteEntry.js",

   },

Note that port 7000 is used here as it is the port we defined when adding module federation in our micro frontend.

Running the project

The ng serve command can be used to serve your host app.
Make use of the ng serve command to serve the micro frontend project.
Open the host application. It is localhost:5000 in our instance.

Add a '/' and the name of the micro frontend after it to access the micro frontend. It will be 'localhost:5000/my-first-mfe' for us. The micro frontend's HTML will show up at the bottom of the host application's content.

Conclusion

Even while the initial setup could seem time-consuming, the process is worthwhile in the end.
Among other benefits, the frontend becomes more tested and reusable when it is as modular as feasible.



AngularJS Hosting Europe - HostForLIFE :: Create a Calculator Application with Bootstrap and Angular

clock February 5, 2024 06:15 by author Peter

I'll walk you through the process of quickly creating a calculator application with Angular and Bootstrap in this post.


Note: Before beginning this session, please read my earlier essay (linked below) about Angular applications.

Step 1 of the Angular Application: Create Component
Make a component called calculator first.
ng g c calculator

Under the calculator folder, this generates calculator.component.ts & calculator.component.html.

Step 2: In calculator.component.ts, add the angular calculator logic.
The selector 'ng-calculator' is used here. in order to use the <ng-calculator></ng-calculator> calculator component anywhere in our code.

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

@Component({
  selector: 'ng-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {

I attach the operand or number that the user clicks to the input variable. For instance, I designate it as the input variable if the user inputs 31+210+40. It makes it simpler to compute the result by simply calling the built-in JavaScript function eval(input). I have some matters to attend to. The user could, for instance, repeat the operands (54++23). or a decimal value that isn't correct, like 54.23.5, etc. Also, if the number starts with 0, eval will generate an error.

The code that follows is prohibited. on multiple occasions. The integers and decimal points are captured here by pressNum. and adds it to the variable used for input. This case has two validations.

input:string = '';
  result:string = '';

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

The code below will fail in strict mode since it does not allow 0 at the beginning and Javascript will throw an error. There can be just one decimal place in an integer.
If the integer starts with 0, Eval will throw an error (Octal literals are not allowed in strict mode). Thus, we eliminate it.
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 returns the last operand. For example, if the user input is 921+18 then the last operand is 18.
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)
  }


The pressOperator captures the operators. It again appends it to the input variable. We make sure that that operator is followed by a number and not another operator (18++).
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();
  }


Here clear removes the last input.
clear() {
    if (this.input !="" ) {
      this.input=this.input.substr(0, this.input.length-1)
    }
  }


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


Here calcAnswer is where the calculation happens. We check the last character. If it is a decimal point (.) then we remove it (Example in 15+13.). We also remove the last character if it is an operator. (Example 15+13+).
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);
  }


Here getAnswer calculates and assigns the result to the input variable.
getAnswer() {
    this.calcAnswer();
    this.input = this.result;
    if (this.input=="0") this.input="";
  }


Then use of constructor() and ngOnInit().
constructor() { }
  ngOnInit(): void {
  }
}


The Code as shown below,
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'ng-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {

  input:string = '';
  result:string = '';

  pressNum(num: string) {

    if (num==".") {
      if (this.input !="" ) {

        const lastNum=this.getLastOperand()
        console.log(lastNum.lastIndexOf("."))
        if (lastNum.lastIndexOf(".") >= 0) return;
      }
    }
    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) {
    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="";
  }
  constructor() { }
  ngOnInit(): void {
  }
}

Step 3. Add Angular template code in calculator.component.html using Bootstrap
<div class="container-fluid">
    <div class="jumbotron col-sm-9 p-2 m-0 bg-warning">
      <h2 class="text-center">Angular Calculator Application</h2>
      <div class="form-group">
        <label for="usr">Displays the User Input</label>
        <div class="form-control" type="text">{{input}}</div>
      </div>
      <div class="form-group">
        <label for="pwd">Displays the Results</label>
        <div class="form-control" 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-danger 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-primary col-sm-3 p-1" type="button" (click)="pressNum('7')">7</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('8')">8</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('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-primary col-sm-3 p-1" type="button" (click)="pressNum('4')">4</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('5')">5</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('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-primary col-sm-3 p-1" type="button" (click)="pressNum('1')">1</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('2')">2</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('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-primary col-sm-3 p-1" type="button" (click)="pressNum('.')">.</button>
        <button class="btn btn-primary col-sm-3 p-1" type="button" (click)="pressNum('0')">0</button>
        <button class="btn btn-lg btn-success col-sm-6 p-1" type="button" (click)="getAnswer()">=</button>
      </div>
    </div>
    </div>


The first textbox displays the user input including the operators.

<div class="container-fluid">
    <div class="jumbotron col-sm-9 p-2 m-0 bg-warning">
      <h2 class="text-center">Angular Calculator Application</h2>
      <h3 class="text-center">By Satyaprakash</h3>
      <div class="form-group">
        <label for="usr">Displays the User Input</label>
        <div class="form-control" type="text">{{input}}</div>
      </div>

Markup

The second textbox displays the result as the user type.
<div class="form-group">
        <label for="pwd">Displays the Results</label>
        <div class="form-control" type="text">{{result}}</div>
      </div>


C clears every display, and x deletes, or clears, the most recent input. Our four operators for division, multiplication, subtraction, addition, and use are /, X,-, and +. to input the digits in decimal. = Computes and resets the input from the user. I'm mapping user clicks to the component class through the usage of event binding. PressNum() records the buttons for numbers and decimals. The button clicks for /, X,-, and + are recorded by the pressOperator() method. All inputs are cleared using allClear. To remove the last input, use clear(). Calculator is reset after calculation using getAnswer().

Step 4. Add the selector of calculator.component.html in app.component.html
<ng-calculator></ng-calculator>

Step 5. Add the CalculatorComponent in the declaration array of app.module.ts
import { CalculatorComponent } from './calculator/calculator.component';

@NgModule({
  declarations: [
    AppComponent,
    CalculatorComponent
  ],


Step 6. Add Bootstrap CDN url in the index.html to make the application responsive design
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular Application Real-Time</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>


Output
Use the below command to run the Angular application.
ng serve



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