Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Change Style Dynamically in Various Ways Using AngularJS

clock November 20, 2024 09:53 by author Peter

This article explains how to change the style dynamically in various ways using AngularJS. AngularJS provides three different ways to change the style dynamically. People always search for methods to change their style dynamically, AngularJS can solve their problems in any of three ways.


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

After downloading the external file you need to add this file to the Head section of your application as in the following.
<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
</head>

Step 2. Now I will create some simple CSS classes to be applied dynamically, or you can say at runtime.
<style>
    .changeColor {
        color: blue;
    }
    .changeSize {
        font-size: 30px;
    }
    .italic {
        font-style: italic;
    }
</style>


Here I have created three classes, namely changeColor, changeSize, and italic. The first CSS Class is used for changing the color of the text to Blue, the second is for changing the text size and the last one is for making the Text Italic.

Now we have created the classes to be applied, we need to work on the ViewModel or design part of our application where simple coding needs to be done to apply the change in CSS.

First Method
In the first method, objects of the classes are created that are called using the ng-model, let's see this by implementing it in our application as in the following.
<p ng-class="{changeColor: Color, changeSize: Size, italic: Italic}">
    Changes Will be Seen in Me
</p>
<input type="checkbox" ng-model="Color"> Change Color (apply "changeColor" class)<br>
<input type="checkbox" ng-model="Size"> Change Size (apply "changeSize" class)<br>
<input type="checkbox" ng-model="Italic"> Make it Italic (apply "italic" class)


Here I have applied the CSS to a <p> Tag, and classes are applied using the ng-class directive, here in the ng-class you can see that I have created an object of each class such as for changeColor, "Color" is created. After this I applied the binding using the ng-model, I created three checkboxes and in each checkbox ng-model is applied, each ng-model provides the binding using the objects created in the ng-class.

So, If we check the first checkbox then the color of the text will change to Blue, similarly, if we check the second and third checkboxes then the text size and its style will change.

Let's see the output.

Output
As I run the application and check the checkboxes then this type of output will be seen.

Second Method
Now, I will show you the Second Method of applying the CSS dynamically. In this method, class names will be called to Apply the CSS.
<p ng-class="style">I Will Show Second Method</p>
<input type="text" ng-model="style" placeholder="Type: changeSize changeColor italic">


Here you can see that in the ng-class I have passed the complete style, since I have passed the style in ng-class it will call all the classes that are created in that style. Then I created a TextBox to which the style is bound using the ng-model, whatever name is provided in the TextBox, the same style will be applied to the text provided through the <p> tag. If the the name provided in the TextBox doesn't match the CSS Class than nothing will happen to the text and nothing will be applied.

Let's see the output.

Output


Third Method
Now, I will show you the Third Method for applying the CSS dynamically.

In this method, CSS classes will be called in the order they were created.
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: changeSize, changeColor or italic"><br>
<input ng-model="style2" placeholder="Type: changeSize, changeColor or italic"><br>
<input ng-model="style3" placeholder="Type: changeSize, changeColor or italic"><br>

Here you can see that I have applied the CSS to the <p> tag using the ng-class but this time I have called the classes by the order they were created, style1 is automatically bound to the first class, similarly style2 and style3 are bound to the second and third class. Then I created three Textboxes that are bound to style 1, 2, and 3 separately, whatever CSS name is provided in these textboxes, the same CSS class will be applied to the Text provided in the <p> tag.

Let's see the output.

Output

The complete code of this application is as follows.
<html ng-app xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
    <title></title>
    <script src="angular.min.js"></script>
    <style>
        .changeColor {
            color: blue;
        }
        .changeSize {
            font-size: 30px;
        }
        .italic {
            font-style: italic;
        }
    </style>
</head>
<body>
    <p ng-class="{changeColor: Color, changeSize: Size, italic: Italic}">Changes Will be Seen in Me</p>
    <input type="checkbox" ng-model="Color"> Change Color (apply "changeColor" class)<br>
    <input type="checkbox" ng-model="Size"> Change Size (apply "changeSize" class)<br>
    <input type="checkbox" ng-model="Italic"> Make it Italic (apply "italic" class)
    <hr>
    <p ng-class="style">I Will Show Second Method</p>
    <input type="text" ng-model="style" placeholder="Type: changeSize changeColor italic">
    <hr>
    <p ng-class="[stle1, stle2, stle3]">I Will Show Third Method</p>
    <input ng-model="stle1" placeholder="Type: changeSize, changeColor or italic"><br>
    <input ng-model="stle2" placeholder="Type: changeSize, changeColor or italic"><br>
    <input ng-model="stle3" placeholder="Type: changeSize, changeColor or italic"><br>
</body>
</html>



AngularJS Hosting Europe - HostForLIFE.eu :: RxJS Operator Essentials: Map, Tap, Filter, and More

clock November 14, 2024 09:21 by author Peter

If you've been working with Angular for a while and find some RxJS pipeable operators slightly confusing, we will explore these familiar operators here.


Great, let’s dive into this exciting topic.

What is an RxJS Operator?
RxJS ships with more than 100 operators.
These operators are one of the building blocks of RxJS.
It is handy for manipulating (process or transform) streams, which are data sequences over time.
Remember that operators are functions, and there are two types of operators.

Let’s see them one by one.

RxJS map Operator

The map function in RxJS is an operator that transforms each emitted value from an observable based on a provided function, returning a new observable with modified values.
Let us see an example.

Creation Operators
We won’t be exploring the creation operator, but it is essential to give an overview. Creation operators are functions that can create an Observable with some expected predefined behavior or by joining other Observables.

Here are some familiar creation operators: of, from, fromEvent, and range.

Let’s have one example.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { from, Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'RxJSOperators';
  subFrom$!: Subscription;

  public ngOnInit(): void {
    this.subFrom$ = from([2, 4, 6, 8]).subscribe({
      next: (item) => console.log(item),
      error: (err) => console.log(err),
      complete: () => console.log('completed')
    });
  }

  public ngOnDestroy(): void {
    this.subFrom$.unsubscribe();
  }
}

From our code example, we have seen that inside the ngOnInit, the from([2,4,6,8]) method creates an observable that emits each number in the array sequentially.

The subscribe method attaches an observer to this observable.

  • First, next, which logs each item emitted.
  • Second, error logs any errors if there’s one.
  • Third, complete which logs “completed” when the observable completes.

Although this is not the main topic of our article, it is a good thing to have an idea.

Pipeable Operators

Pipeable operators are the kind that can be piped to Observables.

Let’s see the syntax below.

observableInstance.pipe(operator);
or
observableInstance.pipe(operatorFactory());


Essentially, the operator and operatorFactory behave as a single method in RxJS. However, there’s a difference between the two. Operator factories are functions that accept parameters to configure their behavior and immediately return operator functions.

Operator functions are the results of these calls (configured functions), which can then transform the observable’s data inside the .pipe().

Let’s see code examples of pipeable operators in the next sections.

RxJS map Operator

The map function in RxJS is an operator that transforms each emitted value from an observable based on a provided function, returning a new observable with modified values.

Let us see an example.


import { Component, OnDestroy, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { from, map, Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'RxJSOperators';
  subCustomer1!: Subscription;

  public ngOnInit(): void {
    const customer$ = from([
      { id: 1, jerseyNumber: 23, age: 61, fullName: "Michael Jordan" },
      { id: 2, jerseyNumber: 23, age: 43, fullName: "Lebron James" },
      { id: 3, jerseyNumber: 24, age: 89, fullName: "Kobe Bryant" }
    ]);

    this.subCustomer1 = customer$
      .pipe(
        map(item => ({
          ...item, shoe: "Nike"
        }))
      )
      .subscribe((result) => console.log(result, "Added Nike shoes"));
  }

  public ngOnDestroy(): void {
    this.subCustomer1.unsubscribe();
  }
}

From our example, the map operator transforms each customer object by adding a new property, shoe, with a value of "Nike". Then, each customer object is spread (...item) to retain the existing properties while adding the shoe property, resulting in a new object.

Finally, log the result to the console with a message saying, "Added Nike shoes". Let’s see the output below.

RxJS tap Operator
The tap function in RxJS is an operator that allows you to perform side effects, like logging or debugging, on each emitted value without altering the observable’s values.

Let us see an example.
import {Component, OnDestroy, OnInit} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {filter, from, map, Subscription, tap} from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements  OnInit, OnDestroy {
  title = 'RxJSOperators';
  subCustomer2!: Subscription;
  public ngOnInit() {
    const customer$ = from([
              { id: 1, jerseyNumber: 23, age: 61, fullName: "Michael Jordan"},
              { id: 2, jerseyNumber: 23, age: 43, fullName: "Lebron James"},
              { id: 3, jerseyNumber: 24, age: 89, fullName: "Kobe Bryant"}
               ]);

    this.subCustomer2 = customer$.pipe(
      tap(item => console.log(item, "Debugging this item before putting Nike shoes")),
      map(item => ({
       ...item, shoe: "Nike"
      })),
      tap(item => console.log(item, "Debugging this item after putting Nike shoes")))
      .subscribe((result) => { console.log(result, "Final result"); });
  }
  public ngOnDestroy() {
    this.subCustomer2.unsubscribe();
  }
}


The first tap operator logs each customer object to the console before transforming. This is useful for debugging, allowing you to inspect the original data emitted by the customer.

Each item is logged with the message "Debugging this item before putting Nike shoes". The map operator transforms each customer object by adding a new property, shoe, with a value of "Nike".

As discussed in the previous example, this operation uses object spread (...item) to retain the original properties while adding the new shoe property, resulting in a modified object for each customer.

The second tap operator logs each transformed customer object, allowing you to verify that the shoe property has been successfully added.

Each item is logged with the message "Debugging this item after putting Nike shoes".

Finally, the subscribe method listens to the transformed observable.

For each item, it logs the final transformed result along with the "Final result" to indicate the completion of the transformation.

Let’s see the output below.

 

RxJS filter Operator
The filter function in RxJS is an operator that emits only the values from an observable that passes a specified condition, effectively filtering out values that don’t meet the criteria.

Let us see an example.
import {Component, OnDestroy, OnInit} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {filter, from, map, Subscription, tap} from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements  OnInit, OnDestroy {
  title = 'RxJSOperators';
  subCustomer3!: Subscription;

  public ngOnInit() {

    const customer$ = from([
               { id: 1, jerseyNumber: 23, age: 61, fullName: "Michael Jordan"},
               { id: 2, jerseyNumber: 23, age: 43, fullName: "Lebron James"},
               { id: 3, jerseyNumber: 24, age: 89, fullName: "Kobe Bryant"}
               ]);

    this.subCustomer3 = customer$.
                             pipe(filter( item => item.jerseyNumber === 23)).
                              subscribe((result) => { console.log(result); });

  }

  public ngOnDestroy() {

    this.subCustomer3.unsubscribe();
  }
}


The filter(item => item.jerseyNumber === 23) filters the data, allowing only objects where jerseyNumber is 23 to pass through the stream. In this example, Michael Jordan and LeBron James meet this condition, while Kobe Bryant does not.

Let’s see the output below.

RxJS take Operator
The take function in RxJS emits only the first specified number of values from an observable and then completes.

Let us see an example.
import {Component, OnDestroy, OnInit} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {filter, from, map, Subscription, take, takeLast, tap} from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements  OnInit, OnDestroy {
  title = 'RxJSOperators';
  subCustomer4!: Subscription;

  public ngOnInit() {

    const customer$ = from([
               { id: 1, jerseyNumber: 23, age: 61, fullName: "Michael Jordan"},
               { id: 2, jerseyNumber: 23, age: 43, fullName: "Lebron James"},
               { id: 3, jerseyNumber: 24, age: 89, fullName: "Kobe Bryant"}
               ]);

    this.subCustomer4 = customer$.
    pipe(
        filter( item => item.jerseyNumber === 23),
        take(1)
        ).
    subscribe((result) => { console.log(result); });

  }

  public ngOnDestroy() {

    this.subCustomer4.unsubscribe();
  }
}

The filter(item => item.jerseyNumber === 23), filters the data to only include customers with a jerseyNumber of 23. This will allow only Michael Jordan and LeBron James through the stream. While take(1) operator limits the stream to emit only the first item that passes the filter condition.

After emitting this first item, it automatically completes the Observable.

Let’s see the output below.

RxJS takeLast Operator
The takeLast function emits only the last specified number of values after the source observable completes.

Let us see an example.
import {Component, OnDestroy, OnInit} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {filter, from, map, Subscription, take, takeLast, tap} from 'rxjs';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements  OnInit, OnDestroy {
  title = 'RxJSOperators';
  subCustomer5!: Subscription;

  public ngOnInit() {

    const customer$ = from([
               { id: 1, jerseyNumber: 23, age: 61, fullName: "Michael Jordan"},
               { id: 2, jerseyNumber: 23, age: 43, fullName: "Lebron James"},
               { id: 3, jerseyNumber: 24, age: 89, fullName: "Kobe Bryant"}
               ]);

    this.subCustomer5 = customer$.
      pipe(takeLast(1)).
      subscribe((result) => { console.log(result); });

  }
  public ngOnDestroy() {

    this.subCustomer5.unsubscribe();
  }
}


The take last operator is used to emit only the last item from the Observable. In this example, takeLast(1) will only emit the very last item in the list—{ id: 3, jersey number: 24, age: 89, fullName: "Kobe Bryant" }—and then complete the Observable.

Summary
In this post, we have discussed RxJS operators and shown the types of operators, such as pipeable and creation operators. We have seen examples of map, tap, filter, take, and takeLast operators. I hope you have enjoyed this article as much as I have enjoyed writing it. Stay tuned for more information, and don't forget to download the attached project source code. If you run the project source code, don’t forget to command “npm install.” Until next time, happy programming, and good luck with your career!



Visual Studio Hosting - HostForLIFE.eu :: Dev Tunnel in Visual Studio Simplifies Local Development

clock November 5, 2024 09:21 by author Peter

Dev Tunnel is a feature introduced in Visual Studio 2022 that simplifies remote debugging and collaboration for developers. It creates a secure tunnel between our local machine and a remote environment, allowing you to access your local applications remotely as if they were running on the remote machine.



This is useful for,

  • Remote debugging: You can set breakpoints, inspect variables, and step through your code as if you were working locally.
  • Collaboration: You can share your local applications with team members or clients, even if they don't have direct access to your development environment.
  • Testing on different devices: You can test your applications on various devices.

(e.g., mobile devices, IoT devices) without requiring them to be on the same network as your development machine.

To use Dev Tunnel

  • Make sure you have Visual Studio 2022 installed with the necessary workloads.
  • In Visual Studio, create a new tunnel by selecting Debug > Dev Tunnels > Create A Tunnel.

Choose the appropriate settings, such as the tunnel type (persistent or temporary) and the authentication method.

Start debugging: Start your application in debug mode, and the tunnel URL will be displayed in the Output window.
Access the application remotely: Use the tunnel URL to access your application from any device with an internet connection.

Dev Tunnel Types
Dev Tunnels come in two primary types, they are,

Temporary Tunnels

  • Created on-demand and exists only for the duration of a debugging session.
  • A new URL is generated each time you start a debugging session.
  • Ideal for quick testing and sharing without long-term access needs.

Persistent Tunnels

  • Remain active even after you close Visual Studio.
  • Maintain the same URL across multiple debugging sessions.
  • Suitable for scenarios where you need consistent access to your application, such as remote collaboration or continuous testing.

Different Types of Access
Dev Tunnels offer flexible access control options as follows,

  • Private
    • Only the creator of the tunnel can access it.
    • Ideal for personal projects or sensitive applications.
  • Organization
    • Members of the same organization as the creator can access the tunnel.
    • Useful for team collaboration within an organization.
  • Public
    • Anyone with the tunnel URL can access it.

Questions & Answers
Is a Microsoft account strictly necessary for accessing dev tunnels?


Yes, we do need a Microsoft account to use Dev Tunnels. This account is used for authentication and authorization purposes to ensure secure access to your local development environment.

Here are the reasons why a Microsoft account is required.

  • Security: By using a Microsoft account, you can control who has access to your Dev Tunnel and protect your sensitive data.
  • Authentication: The Microsoft account verifies your identity and grants you permission to create and use Dev Tunnels.
  • Account Management: Your Microsoft account allows you to manage your Dev Tunnels, including deleting them or modifying their settings.


To use Dev Tunnels, you can sign in with your Microsoft account, Microsoft Entra ID, or GitHub account. Once you're signed in, you can create and manage your Dev Tunnels.

Will the URL change if we close Visual Studio or stop debugging?

Yes, the Dev Tunnel URL will change if you close Visual Studio or stop debugging your application. This is because Dev Tunnels are typically temporary, meaning they are created on-demand and destroyed when the connection is closed.

However, you can create persistent tunnels that will maintain the same URL even after you close Visual Studio.
In conclusion, Dev Tunnel is a powerful tool that can significantly improve your development workflow by making remote debugging and collaboration easier and more efficient. If you're working with remote teams or need to test your applications on different devices, Dev Tunnel is definitely worth considering.



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