Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Angular SSR (server-side rendering)

clock August 12, 2024 10:21 by author Peter

Angular Universal provides server-side rendering (SSR) capabilities for Angular applications. SSR improves performance and SEO by rendering the initial HTML on the server before sending it to the client. This documentation outlines the steps to implement Angular SSR using Angular Universal.

What is client-side rendering (CSR)?
Client-side rendering (CSR) is the process of rendering web pages in the browser using JavaScript. The server sends a minimal HTML file along with JavaScript, which then dynamically generates and updates the content. This approach enables more interactive and responsive web pages by allowing specific parts of the page to be updated without a full page reload.


Server-side rendering (SSR): what is it?
The process of rendering web pages on the server and delivering the completely rendered HTML to the client is known as server-side rendering, or SSR. With this method, the client receives the HTML page in its entirety, generated by the server together with any dynamic data. After that, the client shows the page without doing any additional processing.


Steps to implement Angular SSR using Angular Universal.

Step 1. Set Up Angular Application

Create a new Angular application if you don't have one already.
ng new project-name

Step 2. Add Angular Universal
Add Angular Universal to your application.
ng add @nguniversal/express-engine

Step 3. Add non-destructive hydration

To enable non-destructive hydration, we need to import the provideClientHydration function as the provider of AppModule.
import { provideClientHydration } from '@angular/platform-browser';
// ...

@NgModule({
  // ...
  providers: [provideClientHydration()],  // add this line
  bootstrap: [AppComponent]
})
export class AppModule {
  // ...
}

Step 4. Update the Angular Configuration

Ensure your angular.json includes SSR configurations. This should be done automatically when you add Angular Universal.

Step 5. Update Server Files
const ssrRoutes = ['/test'];

// All regular routes use the Universal engine
server.get('*', (req, res) => {
  if (ssrRoutes.some((route) => req.url.startsWith(route))) {
    res.render(indexHtml, {
      req,
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }]
    });
  } else {
    res.sendFile(join(distFolder, 'index.html'));
  }
});

Step 6. Serve the Application

npm run dev:ssr

Conclusion

By following these steps, you can implement server-side rendering in your Angular application using Angular Universal. SSR enhances performance and improves SEO by serving pre-rendered HTML content to the client.



AngularJS Hosting Europe - HostForLIFE :: Harnessing the Power of Environments using Angular

clock August 5, 2024 08:40 by author Peter

Ever pondered how to call multiple APIs, colors, or headlines for the same application from several environments? Production APIs and test APIs are undoubtedly distinct and need to be utilized extremely carefully. When launching a project, we won't manually alter every API call and sentence structure. This is dangerous and should not be done. With Angular, it's simple to have distinct setups for various environments. Because of this, we can use and deploy to as many environments and stages as necessary without ever having to alter the code. Environment files is the name of it.


To put it briefly, we can have two environment files: environment.development.ts for the development stage and environment.ts for the production stage. The appropriate environment file will then be used, based on where we are distributing our program.

There are very few configurations needed, and there is a significant gain. I'll walk you through the process in this post and give an example of using various texts and APIs.

Getting started
Create a new app: ng new angular-environment-demo --standalone false.
Generate environment files: ng generate environments.

Note. As from the Angular 15.1 environment files are not generated automatically.

Environment file hierarchy
The identical item will initially be present in both the environments.ts and the environments.development.ts. Both objects should have the same key and all settings should be done with them.

For example, you have the following in that file if the environment.development.ts has a key-value pair like: "weather_status": "Good" and the environment.ts will not utilize it. The weather status is ''. This is due to the fact that you are using it in the code, and your code will utilize [this will be explained later] when it looks for it in the environment file. Compilation errors result from your code still searching for this even if it is pointing to another environment file.

Let's create two distinct page titles.

You can utilize the environment file's values in the app.component.ts file or any other ts file by accessing them as follows: environment.\<value you wish to access.>>. Here's an illustration of how to use the pageTitle in the app.component.ts ngOnInit.

Notice the import on line 2. For now, you can import any of the environment files. On line 13, we are assigning the value of ‘pageTitle’ from the environment to ‘this. title’. In the HTML file, we are using the ‘title’ as below.

When you serve the application using: ng serve, you will be given the following screen.

When we do only: “ng serve”, the values from the ‘environment.development.ts’ file are used. If you want to use the configurations from the environment.ts file, you should add the following in the angular.json file.

"fileReplacements": [
  {
    "replace": "src/environments/environment.development.ts",
    "with": "src/environments/environment.ts"
  }
],


These codes should be added under "projects" -> "architect" -> "build" -> "configurations" -> "production" in the angular.json file. Below is a full example of the angular.json file:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular-environment-demo": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "standalone": false
        },
        "@schematics/angular:directive": {
          "standalone": false
        },
        "@schematics/angular:pipe": {
          "standalone": false
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:application",
          "options": {
            "outputPath": "dist/angular-environment-demo",
            "index": "src/index.html",
            "browser": "src/main.ts",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "stagging": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.stagging.ts"
                }
              ]
            },
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.development.ts",
                  "with": "src/environments/environment.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "optimization": false,
              "extractLicenses": false,
              "sourceMap": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.development.ts"
                }
              ]
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "stagging": {
              "buildTarget": "angular-environment-demo:build:stagging"
            },
            "production": {
              "buildTarget": "angular-environment-demo:build:production"
            },
            "development": {
              "buildTarget": "angular-environment-demo:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "buildTarget": "angular-environment-demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        }
      }
    }
  }
}

This file is the most important one when we want to make the best use of an environment file. To use the configuration from the environment.ts file, we need to serve the application with the following command: “ng serve --configuration=production”.

Note that you did not make any changes in the code, you have added only a new configuration and served the app using the new command. For example, if you are serving in production, you can use this command to serve in that environment. No changes in the code are required. It is common to have multiple environments used mostly for testing. When you need to accommodate a new environment, there are some steps to follow.

create a new environment file in the environment folder. For example, we can add environment.staging.ts.
Once this is created, do not forget to add values present in other environment files.

In the angular.json file, we need to add a new configuration under configuration.

The last part is still in the angular.json file. Now we need to add the configuration to serve the application using the respective environment file. These changes are done under "projects" -> "architect" -> "serve" -> "configurations"

We use the following command to serve the application using the settings found in the environment.stagging.ts file: ng serve --configuration=stagging. The screen that loads after serving is as follows.


Using environment files to use different APIs. Another powerful application of environment files is how easily, almost seamlessly it can be used to call different APIs for different environments.

Below are the steps.
Add the corresponding key-value pair in the environment object in all the environment files in your project, like below.
export const environment = {
    pageTitle: "Dinosaur",
    apiUrl: "https://dinosaur-facts-api.shultzlab.com/dinosaurs"
};

In your component.ts file, wherever required, you can call the web service in any method that you want.
For this example, we will be using the fetch method in a promise.
getInfo(){
  const myPromise = new Promise((resolve, reject) => {
    fetch(environment.apiUrl)
    .then((response) => response.json())
    .then((data) => {
      resolve(data)
    })
    .catch((error) => reject(error))
  });

  myPromise
  .then((result: any) => {
    const element = document.getElementById('txtResult');
    if (element) {
      element.innerHTML = JSON.stringify(result.slice(0, 5));
    }
    console.log(result.slice(0, 5));
  })
  .catch((error) => console.log(error))
  .finally(() => console.log('promise done'));
}

Notice that in the call, we are not passing any api. Instead, we are using the variable from the environment file.
At this point, the function is done and can be called when a button is clicked.
When we serve the application using: ng serve and click on the button, we get the following.

When we serve the application using ng serve --configuration=production, below is the output:

  • Note that there has been NO code change. We have only served the application using different serving configurations.
  • The same applies when you are deploying to an environment. Whether you are deploying your Angular app using Azure or something else, you are asked at some point the command to run the Angular application. Providing the correct serving configuration will use the required environment file and will display the corresponding information or call the desired API. No changes in code are required.

Conclusion
Environment files are very important and powerful. Maximizing their use will prevent you from doing manual changes when deploying in different stages.



AngularJS Hosting Europe - HostForLIFE :: How to Copying Text to Clipboard in AngularJS?

clock August 1, 2024 08:52 by author Peter

Web applications frequently need users to copy text to the clipboard in order to share links, copy codes, or accomplish other tasks. We will look at how to add a copy-to-clipboard feature to an AngularJS application in this article.

Required conditions
You need know the fundamentals of JavaScript and AngularJS in order to follow along with this lesson.

Step 1: Configuring the AngularJS Program

Let's start by configuring a basic AngularJS application. Ensure that your HTML file has the AngularJS library.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy to Clipboard in AngularJS</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="clipboardApp" ng-controller="clipboardController">
    <!-- Your AngularJS app content will go here -->
</body>
</html>

Step 2. Creating the AngularJS Module and Controller
Next, let's create an AngularJS module and a controller.
<script>
    var app = angular.module('clipboardApp', []);

    app.controller('clipboardController', ['$scope', function($scope) {
        $scope.textToCopy = "Hello, this is the text to be copied!";

        $scope.copyToClipboard = function() {
            var textArea = document.createElement("textarea");
            textArea.value = $scope.textToCopy;
            document.body.appendChild(textArea);
            textArea.select();

            try {
                document.execCommand('copy');
                alert('Text copied to clipboard');
            } catch (err) {
                console.error('Unable to copy', err);
            }

            document.body.removeChild(textArea);
        };
    }]);
</script>

Step 3. Adding the HTML Elements
Now, let's add the HTML elements to allow users to copy the text.
<div class="container">
    <h1>Copy to Clipboard Example</h1>
    <div class="form-group">
        <label for="textToCopy">Text to Copy:</label>
        <input
            type="text"
            id="textToCopy"
            ng-model="textToCopy"
            class="form-control"
            readonly
        >
    </div>
    <button
        ng-click="copyToClipboard()"
        class="btn btn-primary"
    >
        Copy to Clipboard
    </button>
</div>


Explanation

  • Creating a Textarea Element: In the copy to clipboard function, we create a textarea element dynamically and set its value to the text we want to copy.
  • Appending Textarea to Body: The textarea is appended to the body of the document to ensure it is part of the DOM.
  • Selecting the Text: We then select the text inside the text area.
  • Copying the Text: Using document.execCommand('copy'), we copy the selected text to the clipboard.
  • Removing the Textarea: Finally, we remove the textarea element from the document.


Step 4. Styling the Application
You can add some CSS to style the application.
<style>
    .container {
        margin: 50px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .btn-primary {
        background-color: #007bff;
        border-color: #007bff;
    }
</style>


Example 1

Conclusions

You can incorporate copy-to-clipboard capabilities into your AngularJS application with ease by following these steps. This feature makes it easier for users to copy text without having to pick and paste it by hand, which improves user experience. Play around with this implementation and adjust it to suit the requirements of your application.



AngularJS Hosting Europe - HostForLIFE :: Using Services to Make Angular API Calls

clock July 25, 2024 07:31 by author Peter

Working with APIs is a standard chore in modern web development. Angular's HttpClient module offers a reliable method for managing HTTP requests. You will learn how to create an Angular service that will call an API and manage the responses in this tutorial.

Configuring Angular Project
Make sure you have Angular CLI installed before we begin. If not, you can use the following command to install it.
npm install -g @angular/cli

Create a new Angular project.
ng new api-service-demo
cd api-service-demo


Add HttpClientModule to your project.
ng add @angular/common/http

Creating the Service
Generate a new service using Angular CLI.
ng generate service api

This command will create a file named api.service.ts in the src/app directory.

Importing HttpClient

First, import HttpClient and HttpClientModule in your app.module.ts.
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    // Your components
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    // Other modules
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Implementing the API Call in the Service
Next, implement the API call in your service (api.service.ts).
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

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

  private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // Replace with your API URL

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any> {
    return this.http.get<any>(this.apiUrl);
  }
}


In this example, getPosts is a method that sends a GET request to the specified API URL and returns an Observable of the response.

Using the Service in a Component

Now, let's use this service in a component to fetch data and display it. Generate a new component.ng generate component post-list
Injecting the Service
Inject the ApiService in your post-list.component.ts.import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
  selector: 'app-post-list',
  templateUrl: './post-list.component.html',
  styleUrls: ['./post-list.component.css']
})
export class PostListComponent implements OnInit {

  posts: any[] = [];

  constructor(private apiService: ApiService) { }

  ngOnInit(): void {
    this.apiService.getPosts().subscribe(data => {
      this.posts = data;
    });
  }
}
Displaying Data in the TemplateUpdate the template (post-list.component.html) to display the fetched data.<div *ngIf="posts.length > 0">
  <h2>Posts</h2>
  <ul>
    <li *ngFor="let post of posts">
      <h3>{{ post.title }}</h3>
      <p>{{ post.body }}</p>
    </li>
  </ul>
</div>
<div *ngIf="posts.length === 0">
  <p>No posts available.</p>
</div>


Running the Application
Serve the Angular application using the following command.
ng serve

Navigate to http://localhost:4200 in your browser to see the list of posts fetched from the API.

Conclusion
In this article, we've covered how to make API calls in Angular using a service. We created a service to handle HTTP requests and used this service in a component to fetch and display data. This approach ensures that your API logic is centralized and reusable across different components.



AngularJS Hosting Europe - HostForLIFE :: Highlight Active Menu Item Dynamically in Angular Based on Route

clock July 19, 2024 07:38 by author Peter

Angular's built-in Router module can be used to dynamically highlight the active menu item in an Angular application based on the current path. You can now apply a class to the active link as a result.


Here's how to accomplish it.

Step 1. Import the RouterModule

Ensure that your Angular module—typically app.module.ts—has the RouterModule set.

import { RouterModule } from '@angular/router';
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 2. Update your HTML
Use the routerLinkActive directive to dynamically apply a class to the active menu item. Here’s how you can update your navigation HTML.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Navbar Example</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <style>
    .navbar-nav .nav-item a {
      color: black;
      text-decoration: none;
    }
    .navbar-nav .nav-item a:hover {
      color: #0056b3; /* Optional: Change color on hover */
    }
    .navbar-nav .home-link i {
      color: blue;
    }
    .active-link {
      color: blue !important; /* Customize the active link color */
    }
  </style>
</head>
<body>

<section class="wrapper megamenu-wraper">
  <div class="">
    <nav class="container navbar navbar-expand-lg main-menu">
      <div class="">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item">
              <a routerLink="/private/po" routerLinkActive="active-link" class="home-link active">
                <i class="fa fa-home"></i>
              </a>
            </li>
            <li class="nav-item">
              <a routerLink="dashboard" routerLinkActive="active-link">Dashboard</a>
            </li>
            <li class="nav-item">
              <a routerLink="default" routerLinkActive="active-link">Student List</a>
            </li>
            <li class="nav-item">
              <a routerLink="camps" routerLinkActive="active-link">Activities</a>
            </li>
            <li class="nav-item">
              <a routerLink="camp-attendence" routerLinkActive="active-link">Attendance</a>
            </li>
            <li class="nav-item">
              <a [routerLink]="['/private/po/actvity-camp', 0]" routerLinkActive="active-link">Create Activity</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </div>
</section>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>

Explanation

  • routerLinkActive Directive: This directive applies the specified class (active-link in this case) to the link that matches the current route.
  • routerLink Directive: This binds the link to the router path.
  • CSS: The active-link class is styled to indicate the active state.

Step 3. Ensure router module configuration
Make sure your Angular router is correctly configured in your application module (usually app-routing.module.ts).
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { StudentListComponent } from './student-list/student-list.component';
import { ActivitiesComponent } from './activities/activities.component';
import { AttendanceComponent } from './attendance/attendance.component';
import { CreateActivityComponent } from './create-activity/create-activity.component';
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'default', component: StudentListComponent },
  { path: 'camps', component: ActivitiesComponent },
  { path: 'camp-attendence', component: AttendanceComponent },
  { path: 'private/po/actvity-camp/:id', component: CreateActivityComponent },
  { path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }


This setup ensures that when you navigate through your app, the active link will be highlighted, providing a better user experience.



AngularJS Hosting Europe - HostForLIFE :: Use GitHub Copilot to Learn About Angular Karma Test Cases

clock July 15, 2024 07:55 by author Peter

Make sure you have components and test files for them first. I've made the device.ts and device.test.ts files for this example. Please make use of the pictures below.

Add the required function methods after that. For example, pushToDevice is in charge of pushing data to devices and is also in charge of sending data to the backend.

Add test cases to the device.test.ts file after generating the device.ts and device.test.ts files and including the pushToDevice and sendToBackend methods. Some sample function names that you might use are listed below. If you used the enter tab key to input the function name.

import { describe, expect, test } from '@jest/globals';
import { PushToDevice } from './device';
class Device {
    DeviceID?: number;
    DeviceSerialNumber: string;
}

The copilot will now provide one to five test examples for these techniques. Please see the screenshot up above. The test cases will be executed by Angular. To run and execute the cases, simply type the command "npm run test" into the console. In accordance with the context you supply, it might help by offering several test case samples. This is how these test cases could be organized and run in an Angular project.

The application running time will display if there is a problem. In the event that not, cases ran in the Chrome window opened. Here's what usually occurs when you use Karma (which runs tests in actual browsers like Chrome) and Jasmine to execute tests in an Angular application: When you execute the npm run test in your terminal or command prompt, Karma will record and show this error.

 



AngularJS Hosting Europe - HostForLIFE :: Using Route-Based Angular to Dynamically Highlight the Active Menu Item

clock July 8, 2024 10:08 by author Peter

Angular's built-in Router module can be used to dynamically highlight the active menu item in an Angular application based on the current path. You can now apply a class to the active link as a result.


Here's how to accomplish it.

First, import the RouterModule

Ensure that your Angular module—typically app.module.ts—has the RouterModule set.

import { RouterModule } from '@angular/router';
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 2. Update your HTML
Use the routerLinkActive directive to dynamically apply a class to the active menu item. Here’s how you can update your navigation HTML.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Navbar Example</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <style>
    .navbar-nav .nav-item a {
      color: black;
      text-decoration: none;
    }
    .navbar-nav .nav-item a:hover {
      color: #0056b3; /* Optional: Change color on hover */
    }
    .navbar-nav .home-link i {
      color: blue;
    }
    .active-link {
      color: blue !important; /* Customize the active link color */
    }
  </style>
</head>
<body>

<section class="wrapper megamenu-wraper">
  <div class="">
    <nav class="container navbar navbar-expand-lg main-menu">
      <div class="">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item">
              <a routerLink="/private/po" routerLinkActive="active-link" class="home-link active">
                <i class="fa fa-home"></i>
              </a>
            </li>
            <li class="nav-item">
              <a routerLink="dashboard" routerLinkActive="active-link">Dashboard</a>
            </li>
            <li class="nav-item">
              <a routerLink="default" routerLinkActive="active-link">Student List</a>
            </li>
            <li class="nav-item">
              <a routerLink="camps" routerLinkActive="active-link">Activities</a>
            </li>
            <li class="nav-item">
              <a routerLink="camp-attendence" routerLinkActive="active-link">Attendance</a>
            </li>
            <li class="nav-item">
              <a [routerLink]="['/private/po/actvity-camp', 0]" routerLinkActive="active-link">Create Activity</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </div>
</section>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>


Explanation
routerLinkActive Directive: This directive applies the specified class (active-link in this case) to the link that matches the current route.
routerLink Directive: This binds the link to the router path.
CSS: The active-link class is styled to indicate the active state.

Step 3. Ensure router module configuration
Make sure your Angular router is correctly configured in your application module (usually app-routing.module.ts).
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { StudentListComponent } from './student-list/student-list.component';
import { ActivitiesComponent } from './activities/activities.component';
import { AttendanceComponent } from './attendance/attendance.component';
import { CreateActivityComponent } from './create-activity/create-activity.component';
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'default', component: StudentListComponent },
  { path: 'camps', component: ActivitiesComponent },
  { path: 'camp-attendence', component: AttendanceComponent },
  { path: 'private/po/actvity-camp/:id', component: CreateActivityComponent },
  { path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This setup ensures that when you navigate through your app, the active link will be highlighted, providing a better user experience.



AngularJS Hosting Europe - HostForLIFE :: Dependency Injection System in Angular 18

clock July 4, 2024 07:59 by author Peter

There are many of fascinating new features and enhancements in Angular 18. A notable improvement is the revamped Dependency Injection (DI) framework. Managing the dependencies of components and services is essential to creating scalable and maintainable applications using Angular's DI paradigm. To experience the new DI features in Angular 18, let's explore them in detail and work through an example.

What's New in the DI System of Angular 18?

  • Enhanced Tree-Shakability: Angular 18 makes sure that the final bundle contains only the code that is required. Smaller, more effective applications result from this.
  • Injection Contexts: With the introduction of new injection contexts, developers now have greater power and flexibility in defining and managing various dependency injection contexts.
  • Provider Scopes: Enhancing resource management and efficiency, this new feature gives you more precise control over the lifecycle of dependencies.
  • Simplified Provider Syntax: In Angular 18, a more understandable and maintainable syntax for declaring providers is introduced.

Using the New Dependency Injection Features in Angular 18 as an Example
Let's create a basic Angular 18 application to showcase these latest features in DI. We'll build a service, integrate it with a component, and investigate the recently added DI features.

First Step: Configuring the Angular 18 Project

First, use the Angular CLI to create a new Angular 18 project.

Step 1. Setting Up the Angular 18 Project
First, set up a new Angular 18 project using the Angular CLI
ng new angular18-di-demo
cd angular18-di-demo


Step 2. Creating a Service
We'll create a new service to provide some data to our component. Run the following command to generate the service:
ng generate service data

Open data.service.ts and implement the service like this:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private data = ['Angular 18', 'Dependency Injection', 'New Features'];

  constructor() {}

  getData(): string[] {
    return this.data;
  }
}

Here, the @Injectable decorator with providedIn: 'root' makes this service available throughout the application.

Step 3. Creating a Component
Next, we'll create a component to display the data provided by DataService. Run the following command.
ng generate component data-display

Open data-display.component.ts and inject DataService.
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-data-display',
  templateUrl: './data-display.component.html',
  styleUrls: ['./data-display.component.css']
})
export class DataDisplayComponent implements OnInit {
  data: string[] = [];

  constructor(private dataService: DataService) {}

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

In this component, we inject DataService in the constructor and use it to fetch data in the ngOnInit lifecycle hook.

Step 4. Displaying the Data

Open data-display.component.html and update the template to display the data:
<div>
  <h2>Data from DataService</h2>
  <ul>
    <li *ngFor="let item of data">{{ item }}</li>
  </ul>
</div>

Step 5. Using the Component
Include the DataDisplayComponent in your main application component. Open app.component.html and add the following.
<app-data-display></app-data-display>

Step 6. Running the Application
Run the application using the Angular CLI.

ng serve

Navigate to http://localhost:4200 in your browser. You should see the data displayed from DataService.

Summary

In this article, we've explored the new Dependency Injection features in Angular 18. By creating a simple service and component, we've seen how to use DI in Angular 18. The enhancements in the DI system, such as improved tree-shakability, injection contexts, provider scopes, and simplified syntax, make managing dependencies in Angular applications easier and more efficient. These features will help you maintain a clean and scalable codebase as you build more complex applications.



AngularJS Hosting Europe - HostForLIFE :: Apply Dynamically Changing Filters to Kendo Grid in Angular

clock June 26, 2024 07:59 by author Peter

You may use the built-in features of the Kendo Grid in conjunction with Angular's component lifecycle hooks to apply dynamic filters in a Kendo Grid based on the data type of each column. Here's how you can make this happen.


Install the required packages
Make sure the Angular Grid package's Kendo UI is installed.

npm install @progress/kendo-angular-grid \
            @progress/kendo-angular-inputs \
            @progress/kendo-angular-l10n \
            @progress/kendo-angular-dateinputs \
            @progress/kendo-angular-dropdowns --save


Import Kendo Modules
Import the necessary Kendo UI modules into your Angular module.
import { GridModule } from '@progress/kendo-angular-grid';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
@NgModule({
  imports: [
    GridModule,
    DateInputsModule,
    InputsModule,
    DropDownsModule
    // other imports
  ],
  // other configurations
})
export class AppModule {}


Define the grid in your component template
Create the Kendo Grid in your component template and bind it to a data source.
<kendo-grid [data]="gridData" [filterable]="true">
  <kendo-grid-column *ngFor="let column of columns"
                     [field]="column.field"
                     [title]="column.title"
                     [filter]="getFilterType(column)">
  </kendo-grid-column>
</kendo-grid>


Determine the filter type dynamically
In your component, write a method to return the filter type based on the column's data type.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-dynamic-filter-grid',
  templateUrl: './dynamic-filter-grid.component.html',
  styleUrls: ['./dynamic-filter-grid.component.css']
})
export class DynamicFilterGridComponent implements OnInit {
  public gridData: any[] = [
    { name: 'John', age: 30, birthday: new Date(1990, 1, 1) },
    { name: 'Jane', age: 25, birthday: new Date(1995, 2, 1) },
    // more data
  ];

  public columns: any[] = [
    { field: 'name', title: 'Name', type: 'string' },
    { field: 'age', title: 'Age', type: 'number' },
    { field: 'birthday', title: 'Birthday', type: 'date' }
  ];
  constructor() { }
  ngOnInit(): void { }
  getFilterType(column: any): string {
    switch (column.type) {
      case 'date':
        return 'date';
      case 'number':
        return 'numeric';
      default:
        return 'text';
    }
  }
}


Add the component template

In your component HTML file, use the Kendo Grid and call the dynamic filter method.
<kendo-grid [data]="gridData" [filterable]="true">
  <kendo-grid-column *ngFor="let column of columns"
                     [field]="column.field"
                     [title]="column.title"
                     [filter]="getFilterType(column)">
  </kendo-grid-column>
</kendo-grid>


Conclusion
With these steps, your Kendo Grid will apply filters dynamically based on the data type of each column.



European Node.js Hosting - HostForLIFE :: How to Automate MySQL Database Updates with Cron Jobs in Node.js?

clock June 14, 2024 09:17 by author Peter

Automating repetitive operations is essential for streamlining workflows and increasing productivity in the digital age. An in-depth tutorial on using Node.js and cron jobs to automate MySQL database updates can be found in "How to Automate MySQL Database Updates with Cron Jobs in Node.js: A Step-by-Step Guide".

This article offers developers a workable method for putting scheduled activities into practice, guaranteeing accurate and timely data changes without the need for manual intervention. This book gives you the tools to efficiently use automation, regardless of your level of experience. Whether you're a newbie hoping to improve your backend programming skills or an experienced developer wishing to streamline database administration operations, this guide will help you. Together, let's set out on this path to effective database automation.

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. Install the necessary dependencies (mysql2 and node-cron)
npm install mysql2 node-cron

Step 3. Setting Up the Server
Create the Server File. Create a file named app.js.
const cron = require('node-cron');
const mysql = require('mysql2');

// Create a connection to the MySQL database
const connection = mysql.createConnection({
   host: 'localhost',
  user: 'your_mysql_username',
  password: 'your_mysql_password',
  database: 'your_database_name'
});

// Function to update the MySQL database
const updateDatabase = () => {
  const sql = 'UPDATE users SET last_notification = CURRENT_TIMESTAMP';

  connection.query(sql, (err, result) => {
    if (err) {
      console.error('Error updating database:', err);
      return;
    }
    console.log('Database updated:', result.affectedRows, 'row(s) affected');
  });
};

// Schedule a cron job to update the database every minute
cron.schedule('* * * * *', () => {
  console.log('Scheduling database update...');
  updateDatabase();
}, {
  scheduled: true,
  timezone: 'America/New_York'
});

Step 4. Create a table in the database
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    last_notification TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Step 5. Insert some value manually in the Database

INSERT INTO users (name, last_notification) VALUES
('John Doe', NOW()),
('Jane Smith', NOW());

Step 6. Running the Application
Run the command in CMD.
node app.js

Output

illustrates seamless database management automation. Post-execution, the tutorial ensures continuous updates to the "last_notification" column every minute, facilitating efficient data maintenance and enhancing productivity. Experience streamlined database automation with this comprehensive guide.

Conclusion

The automation of MySQL database updates using Node.js and cron jobs offers significant advantages in streamlining workflows. By implementing the techniques outlined in this guide, developers can ensure continuous and timely updates to their databases, minimizing manual intervention and maximizing efficiency. Embrace the power of automation to unlock greater productivity and reliability in database management.

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

 

 

 



About HostForLIFE

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