Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: How to Make an AngularJS To-Do List?

clock July 9, 2024 08:07 by author Peter

There are multiple processes involved in creating a comprehensive AngularJS to-do list application. I'll walk you through every step of the process here, including adding, modifying, and removing jobs along with the relevant warnings and duplicate value checking.


A List of Tasks in AngularJS
Install the AngularJS application in step 1.

Make the index.html HTML file
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AngularJS To-Do List</title>
    <link rel="stylesheet" href="styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="todoApp" ng-controller="todoController">
    <div class="container">
        <h1>To-Do List</h1>
        <div class="input-group">
            <input type="text" ng-model="newTask" placeholder="Add a new task" class="form-control">
            <button ng-click="addTask()" class="btn btn-primary">Add Task</button>
        </div>
        <div ng-if="alertMessage" class="alert" ng-class="{'alert-success': alertType=='success', 'alert-danger': alertType=='danger'}">
            {{ alertMessage }}
        </div>
        <ul class="list-group">
            <li ng-repeat="task in tasks" class="list-group-item">
                <span ng-if="!task.editing">{{ task.name }}</span>
                <input type="text" ng-if="task.editing" ng-model="task.name" class="form-control">
                <button ng-if="!task.editing" ng-click="editTask(task)" class="btn btn-warning btn-sm">Edit</button>
                <button ng-if="task.editing" ng-click="saveTask(task)" class="btn btn-success btn-sm">Save</button>
                <button ng-click="deleteTask(task)" class="btn btn-danger btn-sm">Delete</button>
            </li>
        </ul>
    </div>
</body>
</html>

Create the AngularJS file (app.js)
var app = angular.module('todoApp', []);
app.controller('todoController', function($scope) {
    $scope.tasks = [];
    $scope.alertMessage = '';
    $scope.alertType = '';
    $scope.addTask = function() {
        if (!$scope.newTask) {
            $scope.showAlert('Task cannot be empty', 'danger');
            return;
        }
        if ($scope.tasks.some(task => task.name === $scope.newTask)) {
            $scope.showAlert('Task already exists', 'danger');
            return;
        }
        $scope.tasks.push({ name: $scope.newTask, editing: false });
        $scope.newTask = '';
        $scope.showAlert('Task added successfully', 'success');
    };
    $scope.editTask = function(task) {
        task.editing = true;
    };
    $scope.saveTask = function(task) {
        if (!$scope.tasks.some(t => t !== task && t.name === task.name)) {
            task.editing = false;
            $scope.showAlert('Task edited successfully', 'success');
        } else {
            $scope.showAlert('Duplicate task name', 'danger');
        }
    };
    $scope.deleteTask = function(task) {
        var index = $scope.tasks.indexOf(task);
        if (index > -1) {
            $scope.tasks.splice(index, 1);
            $scope.showAlert('Task deleted successfully', 'success');
        }
    };
    $scope.showAlert = function(message, type) {
        $scope.alertMessage = message;
        $scope.alertType = type;
        setTimeout(function() {
            $scope.$apply(function() {
                $scope.alertMessage = '';
            });
        }, 3000);
    };
});


Create a CSS file (styles.css) for styling
body {
    font-family: Arial, sans-serif;
    margin: 20px;
}
.container {
    max-width: 600px;
    margin: auto;
}
.input-group {
    display: flex;
    margin-bottom: 20px;
}
.form-control {
    flex: 1;
    padding: 10px;
    font-size: 16px;
}
.btn {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
}
.list-group {
    list-style-type: none;
    padding: 0;
}
.list-group-item {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    background-color: #f9f9f9;
    margin-bottom: 5px;
    border: 1px solid #ddd;
}
.alert {
    padding: 10px;
    margin-bottom: 20px;
}
.alert-success {
    background-color: #d4edda;
    border-color: #c3e6cb;
    color: #155724;
}
.alert-danger {
    background-color: #f8d7da;
    border-color: #f5c6cb;
    color: #721c24;
}


Explanation of the Code
HTML Structure

  • The HTML file sets up the structure of the To-Do list application.
  • It includes an input field for new tasks, a button to add tasks, and a list to display tasks.
  • Each task can be edited or deleted.

AngularJS Controller (app.js)

  • The todoController manages the tasks array and handles adding, editing, and deleting tasks.
  • The addTask function checks for duplicate tasks and alerts the user if a task already exists.
  • The editTask function enables editing mode for a task.
  • The saveTask function saves the edited task and checks for duplicate names.
  • The deleteTask function removes a task from the list.
  • The showAlert function displays an alert message for 3 seconds.

Styling (styles.css)

  • The CSS file styles the To-Do list application, including the input field, buttons, list items, and alert messages.

By following these steps, you can create a fully functional To-Do list application in AngularJS with features like adding, editing, deleting tasks, and handling duplicate tasks with appropriate alerts.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Understanding Data Binding in Angular?

clock July 1, 2024 08:46 by author Peter

With the help of Angular's robust data binding capability, developers can synchronize data between the model and the view. Data binding is one of the ways that Angular enables communication between components and the DOM.


An outline of the primary Angular data binding types can be found here.

1. The use of interpolation

You can insert expressions between the double curly braces ({{ }}) by using interpolation. Data from the component is usually displayed to the view via this.

Usage: {{ expression }}

Example
<button (click)="onClick()">Click me</button>

2. Property Binding
Property binding allows you to bind data from the component to the property of an HTML element or directive. This helps in setting element properties based on component data.
    Usage: [property]="expression"
    Example
   <img [src]="imageUrl">

3. Event Binding
Event binding allows you to respond to user events such as clicks, key presses, and mouse movements. It binds a DOM event to a method in the component.
    Usage: (event)="handler"
    Example

    <button (click)="onClick()">Click me</button>


4. Two-Way Data Binding
Two-way data binding combines property binding and event binding to synchronize data between the model and the view. Angular provides the ngModel directive to facilitate two-way data binding.

    Usage: [(ngModel)]="property"
    Example

    <input [(ngModel)]="name">
    <p>Hello, {{ name }}!</p>


5. Detailed Explanation and Examples
Interpolation: Interpolation evaluates an expression in the context of the current data-bound component. It is useful for embedding dynamic values into the HTML.
Example

    export class AppComponent {
      title = 'Hello, Angular!';
    }


<h1>{{ title }}</h1>

6. Property Binding
Property binding is used to set a property of a view element. It is a one-way data-binding from the component to the view.
Example
export class AppComponent {
  imageUrl = 'https://angular.io/assets/images/logos/angular/angular.svg';
}


<img [src]="imageUrl">

7. Event Binding
Event binding listens to events such as keystrokes, mouse movements, clicks, and touches. When the event is triggered, it calls the specified method in the component.
Example
export class AppComponent {
  onClick() {
    console.log('Button clicked!');
  }
}


<button (click)="onClick()">Click me</button>

8. Two-Way Data Binding
Two-way data binding allows for the automatic synchronization of data between the model and the view. The ngModel directive simplifies this by updating the model whenever the input value changes and updating the input value when the model changes.

Example
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <input [(ngModel)]="name">
    <p>Hello, {{ name }}!</p>
  `
})
export class AppComponent {
  name: string = '';
}


Conclusion
Data binding in Angular facilitates seamless communication between the template (view) and the component (model). It simplifies the process of displaying data, responding to user input, and keeping the view and model synchronized. For more detailed information, you can refer to the official Angular documentation on data binding: Angular Data Binding​​​​​.



AngularJS Hosting Europe - HostForLIFE.eu :: OnPush Change Detection Method: Enhancing Angular Specifications

clock June 24, 2024 09:14 by author Peter

Angular apps frequently have to deal with intricate data binding and frequent updates, which, if not done correctly, can cause performance problems. The OnPush change detection mechanism is a potent tool for performance optimization. In order to assist you in integrating OnPush into your Angular projects, this article explains what it is, how it functions, and offers useful examples.

OnPush change detection: what is it?

When an event, such user input, an HTTP request, or a timer, happens, every component in Angular employs the Default change detection technique by default, which involves checking for changes. Performance bottlenecks may result from this, particularly in large applications.

Performance is enhanced by the OnPush change detection approach, which looks for changes only when:

  • The input attributes of the component alter.
  • The component experiences the triggering of an event.

By using OnPush, you can reduce the number of checks Angular performs, making your application more efficient.
Implementing OnPush change detection

To implement the OnPush strategy, you need to modify the ChangeDetectionStrategy property of your component's decorator. Here's how you can do it:

Step 1. Import ChangeDetectionStrategy and ChangeDetectorRef
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

Step 2. Set ChangeDetectionStrategy to OnPush
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  constructor(private cdr: ChangeDetectorRef) {}
  // Component logic here
}


Step 3. Manage Component Updates
Since OnPush only checks for changes when inputs change, or events occur, you need to handle updates explicitly. For instance, if you update a component's state based on an asynchronous operation, you should manually mark the component for check:
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  data: any;

  constructor(private cdr: ChangeDetectorRef) {}

  updateData(newData: any) {
    this.data = newData;
    this.cdr.markForCheck(); // Explicitly mark for check
  }
}


Practical Example
Here's a complete example demonstrating the OnPush strategy
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input, OnInit } from '@angular/core';
@Component({
  selector: 'app-example',
  template: `
    <div>
      <h1>{{title}}</h1>
      <button (click)="fetchData()">Fetch Data</button>
      <p *ngIf="data">{{data}}</p>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent implements OnInit {
  @Input() title: string;
  data: string;
  constructor(private cdr: ChangeDetectorRef) {}
  ngOnInit(): void {
    // Initialization logic here
  }
  fetchData(): void {
    // Simulate an async operation
    setTimeout(() => {
      this.data = 'New Data Loaded';
      this.cdr.markForCheck(); // Explicitly mark for check
    }, 2000);
  }
}


Benefits of OnPush Change Detection

  • Improved Performance: Reduces unnecessary checks, leading to better performance.
  • Predictable Change Detection: This makes it easier to reason about when and why Angular checks for changes.
  • Efficient Resource Usage: Decreases CPU usage and enhances overall application responsiveness.

Conclusion
Using the OnPush change detection strategy in Angular is a powerful way to optimize your application's performance. By explicitly managing when Angular checks for changes, you can ensure that your application runs more efficiently, especially as it grows in complexity. Implement OnPush in your Angular projects today to experience these performance benefits firsthand.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Work With iframes in Angular?

clock June 13, 2024 09:09 by author Peter

Embedding external material within your Angular component is the process of working with iframes in Angular. You can use the HTML element <iframe> to accomplish this. If necessary, you can also manipulate and engage with the iframe directly from your Angular component. The procedures for integrating and using iframes in an Angular application are listed below.


1. Fundamental Configuration
If you don't currently have an Angular component, start by creating one.
ng generate component iframe-example

2. Embed an Iframe
You can embed an iframe in the component template. Here is a simple example to embed an external website:
iframe-example.component.html

<div class="iframe-container">
  <iframe [src]="iframeUrl" width="100%" height="600px"></iframe>
</div>

iframe-example.component.ts
import { Component } from '@angular/core';
@Component({
  selector: 'app-iframe-example',
  templateUrl: './iframe-example.component.html',
  styleUrls: ['./iframe-example.component.css']
})
export class IframeExampleComponent {
  iframeUrl: string = 'https://www.example.com';
}

3. Dynamic Iframe URLs
You might want to load different URLs dynamically. You can bind the src attribute to a property in your component:
iframe-example.component.html

<div class="iframe-container">
  <iframe [src]="iframeUrl" width="100%" height="600px"></iframe>
</div>
<button (click)="loadUrl('https://www.example.com')">Load Example</button>
<button (click)="loadUrl('https://www.angular.io')">Load Angular</button>


iframe-example.component.ts
import { Component, Sanitizer, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-iframe-example',
  templateUrl: './iframe-example.component.html',
  styleUrls: ['./iframe-example.component.css']
})
export class IframeExampleComponent {
  iframeUrl: any;
  constructor(private sanitizer: DomSanitizer) {
    this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.example.com');
  }
  loadUrl(url: string) {
    this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}


4. Styling the Iframe
You can add styles to the iframe to ensure it fits well within your layout:

iframe-example.component.css

.iframe-container {
  position: relative;
  width: 100%;
  height: 600px;
}
iframe {
  border: none;
  width: 100%;
  height: 100%;
}

5. Interacting with the Iframe
Interacting with the iframe content can be more complex, especially when dealing with different domains due to security constraints (same-origin policy). Here’s an example of how you can post a message to the iframe:
iframe-example.component.html
<div class="iframe-container">
  <iframe #myIframe [src]="iframeUrl" width="100%" height="600px"></iframe>
</div>
<button (click)="sendMessage()">Send Message</button>


iframe-example.component.ts
import { Component, ViewChild, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-iframe-example',
  templateUrl: './iframe-example.component.html',
  styleUrls: ['./iframe-example.component.css']
})
export class IframeExampleComponent {
  @ViewChild('myIframe', { static: false }) myIframe: ElementRef;
  iframeUrl: any;

  constructor(private sanitizer: DomSanitizer) {
    this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.example.com');
  }
  sendMessage() {
    const iframeWindow = this.myIframe.nativeElement.contentWindow;
    iframeWindow.postMessage('Hello from Angular', '*');
  }
}


In the iframe content (if you control it), you can listen for messages:

Content inside the iframe (example.com).
window.addEventListener('message', (event) => {
  console.log('Message received from parent:', event.data);
});


6. Handling messages from the Iframe
You can also listen to messages sent from the iframe to your Angular application:

iframe-example.component.ts
import { Component, HostListener } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
  selector: 'app-iframe-example',
  templateUrl: './iframe-example.component.html',
  styleUrls: ['./iframe-example.component.css']
})
export class IframeExampleComponent {
  iframeUrl: any;

  constructor(private sanitizer: DomSanitizer) {
    this.iframeUrl = this.sanitizer.bypassSecurityTrustResourceUrl('https://www.example.com');
  }
  @HostListener('window:message', ['$event'])
  onMessage(event: MessageEvent) {
    if (event.origin !== 'https://www.example.com') {
      return;
    }
    console.log('Message received from iframe:', event.data);
  }
}


Conclusion
By following these steps, you can effectively embed and interact with iframes in your Angular application. Remember to handle security concerns, such as sanitizing URLs and ensuring that message passing complies with the same-origin policy. This approach allows you to integrate external content and communicate with iframes in a seamless manner.



AngularJS Hosting Europe - HostForLIFE.eu :: Why Better Development With TypeScript Is Better Than JavaScript?

clock June 4, 2024 10:11 by author Peter

Evolution of JavaScript development

  • JavaScript's Development Journey: JavaScript was created in 1995 by Brendan Eich at Netscape Communications to add dynamic and interactive features to web pages. Initially named Mocha and later LiveScript, it was eventually rebranded as JavaScript to take advantage of Java's popularity.
  • Netscape's Involvement and JavaScript's Growth: Netscape included JavaScript in its Navigator browser, making it widely available and popular for web development.
  • ECMA's Role in Standardization: To prevent fragmentation, as other companies like Microsoft created their own versions (e.g., JScript), Netscape submitted JavaScript to ECMA International in 1996. ECMA standardized it as ECMAScript to ensure consistency across different browsers.
  • HTML-JavaScript Synergy: HTML and JavaScript have a complementary relationship in web development. HTML structures and defines the content of a webpage, while JavaScript adds interactivity and dynamic behavior to that content. HTML provides static elements like text, images, and forms, and JavaScript manipulates these elements in response to user actions, enhancing user experience.

Introduction to Angular
Angular is a modern front-end framework developed by Google for building dynamic, interactive single-page applications (SPAs). It uses TypeScript, a superset of JavaScript, as its primary programming language.

Angular's Transformation Over Time
Initially, Angular was developed without TypeScript and focused primarily on client-side development without direct backend interaction. TypeScript was later adopted to enhance development with strong typing and other features.

Exploring TypeScript Integration

  • JavaScript (JS): The base programming language used in web development.
  • TypeScript (TS): A superset of JavaScript developed by Microsoft, adding static types and other features to JavaScript.
  • Angular: Built on top of JavaScript and utilizes TypeScript for development.

Ownership and Collaborations

  • Angular: Developed and maintained by Google.
  • TypeScript: Developed and maintained by Microsoft.

While Angular is a Google-developed framework, it relies on TypeScript, which is developed by Microsoft. This collaboration enhances the capabilities and performance of Angular applications, benefiting from TypeScript's strong typing and other advanced features.

Why Angular When JavaScript Is There

Addressing Complexity in Web Development

The need for Angular arises due to several factors

  • Complexity Management: As web applications grew in complexity, developers needed a more structured approach to manage code, dependencies, and scalability.
  • Reusability: Angular facilitates component-based architecture for reusability.
  • Data Binding: Angular provides two-way data binding, enabling synchronization between model and view.
  • Dependency Injection: Angular's dependency injection system enhances modularity and testability.
  • Tooling: Angular offers a comprehensive set of tools for development and testing.
  • Enterprise-level Development: Angular supports large-scale, enterprise-level application development.

Why TypeScript When JavaScript Is There

TypeScript is preferred for

  • Static typing: TypeScript offers static typing, aiding in early error detection and improving code reliability.
  • Enhanced IDE support: TypeScript boosts developer productivity with features such as code completion, refactoring tools, and intelligent code analysis.
  • Modern JavaScript features: TypeScript introduces modern JavaScript features such as classes, interfaces, enums, generics, async/await, and more, enhancing the language's capabilities and expressiveness.

Conclusion
In modern web development, TypeScript offers clear advantages over JavaScript. Its static typing enhances code reliability, catching errors early in the development process. Combined with IDE support for productivity and modern JavaScript features, TypeScript provides developers with a powerful toolkit for building scalable applications. Choosing TypeScript is a strategic move toward achieving excellence in web development.



AngularJS Hosting Europe - HostForLIFE.eu :: The Distinction Between Vue, React, and Angular.js

clock May 22, 2024 08:11 by author Peter

Three front-end frameworks have become well-known in the constantly changing field of web development: Angular, React, and Vue.js. These technologies each address contemporary coding difficulties in a different way, and each has special strengths and use cases. This blog examines their development, history, and salient characteristics to assist you in selecting the best one for your upcoming undertaking.

Angular The all-encompassing structure
Evolution and History

Angular's Model-View-Controller (MVC) architecture and two-way data binding transformed front-end development when it was first released by Google in 2010 under the name AngularJS. A comprehensive overhaul of AngularJS, Google launched Angular (also known as Angular 2+) in 2016 to solve the shortcomings of the original framework and meet the demands of contemporary web development.

Key Features

  • TypeScript: Angular is built using TypeScript, a statically typed superset of JavaScript, enhancing code quality and maintainability.
  • Comprehensive Toolset: Angular offers a full-fledged framework with tools and libraries for routing, form handling, HTTP client, and more.
  • Two-way Data Binding: Simplifies the synchronization between the model and the view, making development more intuitive.
  • Dependency Injection: Enhances modularity and reusability of components by injecting dependencies where needed.


Use Cases
Angular is ideal for large-scale enterprise applications where a robust, scalable, and maintainable solution is required. Its comprehensive nature allows for the development of complex, feature-rich applications.

React The flexible library

History and Evolution
React was developed by Facebook and released in 2013. Unlike Angular, React is a library focused on building user interfaces, particularly single-page applications. It introduced the concept of a virtual DOM and component-based architecture, which significantly improved performance and developer productivity.

Key Features

  • Virtual DOM: React’s virtual DOM improves performance by minimizing direct manipulations of the real DOM.
  • Component-Based Architecture: Promotes reusable, self-contained components, making the development process modular and manageable.
  • JSX Syntax: Allows developers to write HTML-like code within JavaScript, streamlining the creation of UI components.
  • Unidirectional Data Flow: Simplifies data management and debugging by ensuring data flows in a single direction through the application.


Use Cases
React is suited for dynamic and high-performing applications, such as social media platforms, e-commerce sites, and content management systems. Its flexibility and performance benefits make it a popular choice among developers.

Vue.js The progressive framework

History and Evolution
Vue.js was created by Evan You and released in 2014. It was designed to be an approachable and versatile framework, combining the best features of Angular and React while offering a gentle learning curve. Vue has grown rapidly in popularity due to its simplicity and powerful features.

Key Features

  • Reactive Data Binding: Simplifies the connection between the model and the view, making development intuitive.
  • Component-Based Architecture: Encourages the use of reusable, modular components.
  • Single-File Components: Allows developers to encapsulate HTML, CSS, and JavaScript within a single file, promoting better organization and maintainability.
  • Flexibility: Vue can function as a library for enhancing existing projects or as a full-fledged framework for new applications.


Use Cases
Vue.js is perfect for both small and large-scale applications. Its progressive nature allows developers to incrementally adopt its features, making it a flexible choice for projects of varying complexity.

Angular vs React vs Vue.js

Feature Angular React Vue.js
Initial Release 2010 (AngularJS), 2016 (Angular) 2013 2014
Developed By Google Facebook Evan You (Open Source)
Language TypeScript JavaScript (JSX) JavaScript
Architecture MVC, Component-based Component-based Component-based
Data Binding Two-way One-way Two-way
Performance Good Excellent Excellent
Learning Curve Steep Moderate Gentle
Use Case Large enterprise applications Dynamic, high-performing apps Flexible, any size applications

 



AngularJS Hosting Europe - HostForLIFE.eu :: startWith() Operator in Angular

clock May 15, 2024 08:44 by author Peter

The RxJS library's Angular module's startWith() operator is used to prepend a starting value or set of values to the start of an observable series. This operator makes sure that these initial values are released as soon as the observable is subscribed, before it starts to release its typical series of values.


Setting up

Make sure your Angular project has RxJS installed. If it's not installed already, npm can be used to add it:

Usage
Import the startWith operator from RxJS in the component or service where you want to use it:
import { startWith } from 'rxjs/operators';

Example
Let's illustrate how startWith() works with a practical example.

Service Definition

Assume you have a service that provides an observable stream of numbers:
import { Injectable } from '@angular/core';
import { Observable, interval } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class NumberService {

  getNumbers(): Observable<number> {
    return interval(1000); // Emits incremental numbers every second
  }
}


Component Implementation

In your component, you can consume this service and use the startWith() operator to prepend an initial value before the stream of numbers starts emitting.
import { Component, OnInit } from '@angular/core';
import { NumberService } from './number.service';
import { startWith } from 'rxjs/operators';

@Component({
  selector: 'app-number-display',
  template: `
    <h2>Number Stream</h2>
    <ul>
      <li *ngFor="let number of numberStream$ | async">{{ number }}</li>
    </ul>
  `
})
export class NumberDisplayComponent implements OnInit {

  numberStream$: Observable<number>;

  constructor(private numberService: NumberService) { }

  ngOnInit(): void {
    this.numberStream$ = this.numberService.getNumbers().pipe(
      startWith(0) // Prepend 0 as the initial value
    );
  }

}


In this example

  • this.numberService.getNumbers() returns an observable that emits incremental numbers every second using interval(1000).
  • startWith(0) is used within the pipe() method to prepend the initial value 0 to the beginning of the observable sequence. This means that 0 will be emitted immediately upon subscription, before the interval starts emitting numbers.

Template Usage
In the component's template (number-display.component.html), subscribe to numberStream$ using the async pipe to display the emitted numbers:
<h2>Number Stream</h2>
<ul>
  <li *ngFor="let number of numberStream$ | async">{{ number }}</li>
</ul>




AngularJS Hosting Europe - HostForLIFE.eu :: How to Install an Angular 17 Application Without Cost?

clock May 7, 2024 07:17 by author Peter

Google offers the Firebase Console for free hosting of your Angular application. With Firebase, you can create and expand popular apps and games that users like. endorsed by Google and relied upon by millions of companies worldwide.

Login to firebase with your google account.
https://firebase.google.com

Create Angular 17 Application using Angular CLI

As of today (May 5th, 2024) Angular 17.3.6 is the latest version.
We can upgrade our Angular CLI to latest version.

C:\Users\peter>npm install @angular/cli -g

We can upgrade the npm also
npm install -g [email protected]

We can check the Angular CLI version now.

We can create an Angular application now.
D:\Work\Angular\001>ng new AngularGlobe

After installing the packaging, we can go to the application in Visual Studio Code by Microsoft.

We can run the angular application by below command.
ng serve

We can add our globe image in app.component.html file with a small style class in app.component.css as well.

app.component.html

<h1>
  <img src="../assets/Our_Moon_Phases_and_Eclipses.gif" class="center">
</h1>
<p class="center">

  <a href="https://www.esa.int/" target="_blank">Image Courtesy : THE EUROPEAN SPACE AGENCY</a>
</p>

app.component.css
.center {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 50%;
  }

Login Firebase Console with Google account.
We can give a name to our Angular project.

Configure google analytics.

Various options available in Firebase. You can explore each feature.

We can focus on Hosting options.

We have to install firebase-tools
npm install -g firebase-tools
firebase login


Proceed Yes

You can select the hosting option with space bar.
We have already created a project in Firebase.
Please select the project with existing project option.

Now we must select the build folder.

Before selecting the build folder we can build our project using below command.

ng build

Now we have choose the build folder.

NB: The deployment path has been modified by the Angular team to dist\<project name>\browser.

This allows us to deploy the application at this time.

Firebase Deploy

Application is deployed to https://angular-globe.web.app

If needed, you can purchase a domain from GoDaddy or BlueHost and link with Firebase free domain.



AngularJS Hosting Europe - HostForLIFE.eu :: Angular v16: Data Exchange Between Parent & Child Components

clock April 30, 2024 10:36 by author Peter

In Angular development, effective communication between parent and child components is essential for creating dynamic and interactive apps. We will explore two essential data exchange techniques in this extensive guide: sending data from a parent component to a child component and receiving data in return from a child component to a parent component. Join us as we thoroughly examine each technique, offering concise explanations and helpful code samples all along the way.

Data Transmission from Parent to Child:
Step 1: In the parent component, define the data Define the data that will be sent to the child component in the parent component (Parent.component.ts).

export class ParentComponent
{
  data: string = 'This is data from the parent component';
}

Explanation. Here, we define a variable data in the parent component to hold the information that will be sent to the child component.

Step 2. Pass Data to Child Component In the parent component template (Parent.component.html), use property binding to pass the data to the child component.
<app-child [childData]="data"></app-child>

Explanation. We use property binding to bind the data variable from the parent component to the childData input property of the child component.

Step 3. Receive Data in Child Component In the child component (Child.component.ts), use the @Input decorator to receive the data from the parent component.
export class ChildComponent
{
  @Input() childData: string | undefined | any;
}

Explanation. Here, we use the @Input decorator to define an input property childData, which will receive the data passed from the parent component.

Step 4. Display Data in Child Component In the child component template (header.component.html), display the received data.
<p>{{childData}}</p>

Explanation. We simply display the childData received from the parent component within the child component's template.

Sending Data from Child to Parent Component:
Step 1. Define Event in Child Component In the child component (Child.component.ts), define an event emitter to send data to the parent component.
export class ChildComponent
{
  data: string = 'This is data from the child component';
  @Output() dataSent = new EventEmitter<string>();

  sendDataToParent(): void
  {
    this.dataSent.emit(this.data);
  }
}


Explanation. Here, we define an event emitter, dataSent, which emits data of type string. We also create a method sendDataToParent() to emit the data when called.

Step 2. Receive Data in Parent Component In the parent component (Parent.component.ts), define a method to receive the data from the child component.
export class ParentComponent
{
  receivedData: string | undefined;

  onDataReceived(data: string): void
  {
    this.receivedData = data;
  }
}

Explanation. We define a method onDataReceived() in the parent component to handle the data received from the child component.

Step 3. Handle Data Event in Parent Component Template In the parent component template (Parent.component.html), bind to the data event emitted by the child component and handle it using the method defined in Step 2.
<app-child (dataSent)="onDataReceived($event)"></app-child>

Explanation. Here, we bind to the dataSent event emitted by the child component and call the onDataReceived() method in the parent component, passing the received data as an argument.

Conclusion

By meticulously following these step-by-step instructions, you can seamlessly achieve data exchange between parent and child components in Angular v16. Whether transmitting data from a parent component to a child component or vice versa, these techniques empower you to craft immersive and interactive user experiences within your Angular applications. Unlock the full potential of Angular v16 and elevate your development prowess with these essential data communication methods.



Node.js Hosting Europe - HostForLIFE.eu :: How to Create a Node.js Logging System with Express?

clock April 25, 2024 13:50 by author Peter

In contemporary web development, logging plays a crucial role in program monitoring and troubleshooting. Node.js offers a variety of logging tools for monitoring and analyzing application operations because of its event-driven architecture. This article will walk through how to build a logging system for a Node.js application using Winston, a versatile logging package, and Express, a popular web framework.

What is Logging?
The process of keeping track of activities and occurrences inside a software system is called logging. These log entries help with debugging, monitoring, auditing, and security. They include timestamps, severity levels, messages, and contextual data. Logging helps with performance analysis, intrusion detection, compliance adherence, and troubleshooting by capturing important information about system behavior. With their ability to provide insights into application flow, performance bottlenecks, user actions, and security concerns, logs are an indispensable tool for developers, administrators, and security professionals. Logging is essentially a basic procedure used in software development and operations that makes software systems easier to manage, secure, and monitor.

Why we use Logging?

Logging serves several essential purposes in software development:

  • Debugging and Troubleshooting: Logs are an important source of information for troubleshooting and identifying difficulties with a program. To comprehend the execution flow, spot faults, and find the source of problems, developers can go through log messages.
  • Monitoring and Performance Optimization: Developers may keep an eye on an application's performance in real time with the help of logs. Developers can pinpoint performance bottlenecks, maximize resource use, and raise the application's general effectiveness by examining log data.
  • Auditing and Compliance: Keeping track of user actions and system events is facilitated by logging. For compliance with legal standards like GDPR, HIPAA, or PCI DSS, this audit trail is crucial. Logs are useful for monitoring user behavior, spotting illegal access, and guaranteeing the accuracy of data.
  • Security and Intrusion Detection: When it comes to identifying security risks and unauthorized access attempts, logs are essential. Events including unsuccessful login attempts, questionable activity, and possible security breaches are recorded in security logs. Administrators are able to quickly identify and address security incidents by examining security logs.

Steps for Creating a Project
Step 1.  Setting Up the Project
Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.

Step 2. Integrating Winston for Logging

Winston is a versatile Node.js logging package that supports many transports, such as file, database, and terminal. Winston will be set up to log messages to both the console and a log file at various levels (info, error, etc.).
// main.js

const winston = require('winston');

// Create a logger instance
const logger = winston.createLogger({
  level: 'info', // Logging level
  format: winston.format.json(), // Log format
  transports: [
    // Log to the console
    new winston.transports.Console(),
    // Log to a file
    new winston.transports.File({ filename: 'logging_file.log' })
  ]
});


Step 3.  Implementing Logging Middleware in Express
We are able to intercept and handle incoming requests thanks to express middleware. A unique middleware function will be developed to log incoming HTTP requests. Request methods, URLs, and other pertinent data will be recorded by this middleware and logged using Winston.
// Middleware to log requests
app.use((req, res, next) => {
  logger.log('info', `${req.method} ${req.url}`);
  next();
});

Step 4.  Creating Routes and Handling Errors
After installing logging middleware, we will create our Express application's routes. To show how to handle requests, we'll construct a simple route for the main page ("/"). Furthermore, error handling middleware will be implemented to log and manage any faults that arise during request processing.
// Route handling
app.get('/', (req, res) => {
  res.send('Hello, world!');
});

// Error handling middleware
app.use((err, req, res, next) => {
  logger.log('error', err.stack);
  res.status(500).send('Something broke!');
});


Step 5. Serving Log File via Web Interface
We'll develop an additional route ("/logs") that reads the contents of the log file and sends it to the client in order to give a user-friendly way for log files to be viewed. In order to ensure security and avoid dangerous infinite loops, this route will ignore logging requests so they are not kept in the log file.
// Route to serve log file
app.get('/logs', (req, res) => {
  fs.readFile('combined.log', 'utf8', (err, data) => {
    if (err) {
      logger.log('error', err);
      return res.status(500).send('Error reading log file');
    }
    res.type('text/plain').send(data);
  });
});


Step 6. Running the Application

Finally, let us launch our Express application and verify its operation. To start the HTTP request logging, start the server and visit the home page. You may also view the contents of the log file using the web interface by going to the "/logs" route.
node main.js

Output



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