Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Using Angular CLI 17.0.6, Node: 20.0.1, and npm 10.2.3 on Windows, Create Your First Angular

clock December 19, 2023 06:08 by author Peter

On November 6, 2023, Angular 17 was launched, and I wanted to create my first application with it. These instructions will help you create your first Angular 17 application. With the exception of a few advanced capabilities that must be enabled, this is essentially the same if you have expertise with earlier Angular versions. In addition to a fresh style, Angular 17 introduces several new capabilities for developers and performance. Additionally, Angular17 has well-managed documentation.

Developing an Angular 17 Application
Required conditions

Install the most recent LTS version of NODE JS. I've utilized 20.10.0. Installing and downloading this can be done at https://nodejs.org/en.
During installation, make sure to tick the set Path in the Environment Variables option.

Installing Angular CLI is a required that will be done concurrently with node js installation.
After the installation is complete, use CMD to verify the installed version of the node.

Enter "node -v" in the command window. This screen grab below displays the version that I have installed.

After Node js has been successfully installed, Typescript needs to be installed. Try using the admin version of cmd. Given that folder rights were restricted, I knew I had to take this action. I've included some instructions below in case you're operating through a proxy.

CMD "npm install –g typescript" should be run.

if any of the following mistakes happen. CERT_IN_CHAIN_SELF SIGNED.

I got around the certificate, which is the above error, with this cmd. "npm config set strict-ssl false" Strict SSL configuration will now be set to false. If the installation goes well, it will seem like the screen below, which indicates that the installation was successful.

Run the command "npm install -g @angular/cli@latest" as shown above the screen. It does say about funding which is to ask for funds.
Some of these packages installed are probably asking for funds. (optional)

You can check the version installed using the command "ng version"

Now that the prerequisites have been met, use the command "ng new {APPName}" to begin building a new Angular17 application. The CLI will inquire about the type of styling you want to use and whether you need to enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering) when you create a new application.

When user interaction with the backend is required, server-side rendering is employed.

To launch the ng serve –o application, use this command. Your browser will launch it at http://localhost:4200/.


Thank you, and Hopefully, this article helped you get started with creating an angular 17 application.



AngularJS Hosting Europe - HostForLIFE :: ng-container, ng-template, and ng-content

clock August 25, 2023 08:22 by author Peter

ng-container
By enabling you to apply Angular directives without including additional items in the DOM (Document Object Model), the ng-container functions as a kind of transparent container. It is frequently employed when you wish to structure or conditionally include elements in your template.


As an illustration, consider creating a product page. If the product is in stock, you want to display the product details; otherwise, you want to display a notification stating the product is unavailable.

<ng-container *ngIf="productAvailable; else outOfStockTemplate">
  <div>Product Name: {{ productName }}</div>
  <div>Price: {{ productPrice }}</div>
</ng-container>

<ng-template #outOfStockTemplate>
  <div>This product is currently out of stock.</div>
</ng-template>

ng-template
The ng-template is like a template blueprint that doesn't get displayed immediately. It's used to define sections of your template that can be reused and conditionally rendered using structural directives.

Example: Let's say you're creating a list of blog posts. You want to show different styles for featured posts and regular posts.
<ul>
  <ng-container *ngFor="let post of posts">
    <ng-container *ngTemplateOutlet="post.featured ? featuredTemplate : regularTemplate; context: { post: post }"></ng-container>
  </ng-container>
</ul>

<ng-template #featuredTemplate let-post>
  <li class="featured">{{ post.title }}</li>
</ng-template>

<ng-template #regularTemplate let-post>
  <li>{{ post.title }}</li>
</ng-template>


ng-content
The ng-content is used to allow external content to be included within the template of your component. It's ideal for making more adaptable components that can be used in a variety of situations. Consider designing a card component that can display a variety of content.
<div class="card">
  <div class="card-header">
    <ng-content select=".card-title"></ng-content>
  </div>
  <div class="card-content">
    <ng-content></ng-content>
  </div>
  <div class="card-footer">
    <ng-content select=".card-actions"></ng-content>
  </div>
</div>


Now, when you use this component, you can provide custom content for each section:
<app-card>
  <div class="card-title">Card Title</div>
  <p>This is the content of the card.</p>
  <div class="card-actions">
    <button>Edit</button>
    <button>Delete</button>
  </div>
</app-card>


By combining these concepts, you can create components that are more dynamic and adaptable. ng-container, ng-template, and ng-content help you organize and structure your templates in a way that makes your code more readable and maintainable.



AngularJS Hosting Europe - HostForLIFE :: Important RxJS Operators

clock August 21, 2023 08:54 by author Peter

RxJS (Reactive Extensions for JavaScript) is a sophisticated tool used in Angular applications for handling asynchronous and event-based programming with observables. RxJS provides a diverse set of operators for manipulating, transforming, combining, and managing observables in a flexible and functional manner. These operators facilitate reactively working with data streams and asynchronous processes.


Here's a rundown of some of the most common RxJS operators and how they can be utilized in Angular:
map

The map operator is used to transform observable values into new ones. This is frequently used to do data transformations.

import { map } from 'rxjs/operators';

observable.pipe(
  map(data => data * 2)
).subscribe(result => console.log(result));


filter
The filter operator is used to remove values from an observable depending on a criterion.
import { filter } from 'rxjs/operators';

observable.pipe(
  filter(data => data > 5)
).subscribe(result => console.log(result));


mergeMap (flatMap)
The mergeMap operator is used to merge multiple observables into a single observable by applying a function to each emitted value and flattening the resulting observables.
import { mergeMap } from 'rxjs/operators';

observable.pipe(
  mergeMap(data => anotherObservable(data))
).subscribe(result => console.log(result));


switchMap
The switchMap the operator is similar to mergeMap, but it switches to a new inner observable whenever a new value is emitted from the source observable, canceling the previous inner observable.
import { switchMap } from 'rxjs/operators';

observable.pipe(
  switchMap(data => anotherObservable(data))
).subscribe(result => console.log(result));


debounceTime
The debounceTime operator delays emitted values for a specified amount of time and only emits the last value within that time frame.
import { debounceTime } from 'rxjs/operators';
inputObservable.pipe(
  debounceTime(300)
).subscribe(value => console.log(value));

combineLatest
The combineLatest operator combines the latest values from multiple observables whenever any of the observables emit a new value.
import { combineLatest } from 'rxjs/operators';

combineLatest(observable1, observable2).subscribe(([value1, value2]) => {
  console.log(value1, value2);
});

catchError
The catchError operator is used to handle errors emitted by an observable by providing an alternative observable or value.
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';

observable.pipe(
  catchError(error => of('An error occurred: ' + error))
).subscribe(result => console.log(result));


These are just a few examples of the many RxJS operators available. Using RxJS operators effectively can help you manage complex asynchronous workflows, handle data transformations, and create more responsive and reactive Angular applications.

Happy Learning :)



AngularJS Hosting Europe - HostForLIFE :: Improving Performance through Angular Change Detection Techniques

clock May 19, 2023 08:27 by author Peter

Change detection is an integral component of Angular that ensures the user interface is in alignment with the state of the application. ChangeDetectionStrategy is Angular's default detection strategy.Standard, which examines for modifications to all components and their templates on each JavaScript event or timer tick.


Nevertheless, this default strategy may result in superfluous and expensive change detection cycles, particularly in large-scale applications. Alternative strategies, such as OnPush, enter into play at this point. The OnPush strategy optimizes change detection by focusing solely on a component's inputs and references.

Using the OnPush strategy, Angular determines if a component's input properties have changed. If the input values remain the same, Angular assumes that the component's state hasn't changed and skips its change detection entirely. This optimization can significantly improve the performance of your Angular application, especially when used strategically.

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

@Component({
  selector: 'app-user',
  template: `
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
  @Input() user: User;
}

In this example, the UserComponent has the OnPush change detection strategy defined. By doing so, we instruct Angular to only perform change detection if the user input property changes.

When using the OnPush strategy, it is essential to ensure that the user input property is immutable. If you update the user object's properties, Angular won't detect the changes, as it relies on reference comparison.

To optimize performance further, you can utilize the ChangeDetectorRef to manually trigger change detection when necessary:

import { Component, Input, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-user',
  template: `
    <h2>{{ user.name }}</h2>
    <p>{{ user.email }}</p>
    <button (click)="updateUser()">Update</button>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
  @Input() user: User;

  constructor(private cdr: ChangeDetectorRef) {}

  updateUser() {
    // Update the user object
    this.cdr.markForCheck(); // Trigger change detection
  }
}


In the above example, we inject the ChangeDetectorRef and call its markForCheck() method to manually trigger change detection when the user clicks the "Update" button.

By understanding and utilizing Angular's change detection strategies, especially the OnPush strategy, you can significantly enhance the performance of your Angular applications. By minimizing unnecessary change detection cycles, your app will run more efficiently and provide a smoother user experience.

Remember to carefully analyze your application's requirements and components' state before choosing a change detection strategy. Applying the OnPush strategy to components that rarely change or have immutable input properties can lead to noticeable performance improvements.



AngularJS Hosting Europe - HostForLIFE :: Interceptors In Angular Along With Benefits

clock April 10, 2023 08:33 by author Peter

In Angular, an interceptor is a middleware that intercepts HTTP requests and responses. Interceptors are used to manipulate or transform HTTP requests and responses globally. This means you can modify HTTP requests and responses in one place and affect all the requests and responses that go through that place.

 

Ininterceptors In Angular
Interceptors are a powerful tool in Angular as they can be used for a wide variety of tasks, such as,
    Adding authorization headers to requests
    Logging requests and responses
    Adding or removing parameters from requests
    Transforming response data

How to implement an interceptor in Angular?
To implement an interceptor in Angular, you need to create a class that implements the HttpInterceptor interface. The HttpInterceptor interface has two methods to implement: intercept() and, optionally, handleError().

So let's start. Here's an example of an interceptor that adds an authorization header to every HTTP request,
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
        // Get the access token from your authentication service
        const accessToken = this.authService.getAccessToken();
        // Clone the request and add the authorization header
        const authRequest = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        });
        // Pass the cloned request to the next handler in the chain
        return next.handle(authRequest);
    }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and overrides the intercept() method. In the intercept() method, we get the access token from our authentication service and clone the incoming request, adding an authorization header. We then pass the cloned request to the next handler in the chain using the next.handle() method.

To use this interceptor, register it with the Angular HTTP client. You can do this by providing it in the provider's array of your AppModule,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AuthInterceptor } from './auth.interceptor';

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
    }]
})
export class AppModule {}


In this example, we import the HttpClientModule and our AuthInterceptor class. We then provide our interceptor in the provider's array using the HTTP_INTERCEPTORS token. The multi-option is set to true, which means that this interceptor is added to the existing array of HTTP interceptors rather than replacing it.
Benefits of using interceptors in Angular

    Interceptors allow the manipulation of HTTP requests and responses globally, making it easy to implement cross-cutting concerns such as authentication and error handling.
    Interceptors can reduce code duplication by providing a centralized place to modify requests and responses.
    Interceptors can be easily added or removed, making it easy to change the behavior of your application without having to modify every HTTP request and response.

Summary
Interceptors are a powerful Angular tool that allows you to manipulate HTTP requests and responses globally. They can be used for various tasks and provide a centralized place to modify requests and responses. By using interceptors, you can reduce code duplication and easily add or remove functionality from your application.



AngularJS Hosting Europe - HostForLIFE :: TypeScript Versions In Angular

clock March 14, 2023 07:24 by author Peter

TypeScript is a superset of JavaScript and is widely used for developing large-scale applications. Angular, one of the most popular front-end frameworks is built using TypeScript. When working with Angular, knowing which version of TypeScript is being used in your project is important. In this blog post, we'll discuss identifying the TypeScript version in an Angular project.


Angular uses TypeScript as its primary language, meaning you will need to have TypeScript installed on your machine to develop Angular applications. Once you have TypeScript installed, you can check the version of TypeScript in your Angular project in the following ways:

Package.json file
The TypeScript version can be found in the package.json file of your Angular project. Open the package.json file and look for the "typescript" section. You will see the version of TypeScript that your Angular project is using. For example:
"devDependencies": {
   "typescript": "^4.3.5"
}

Angular CLI
You can also check the TypeScript version using the Angular CLI. Open your terminal and run the following command in the root directory of your Angular project:
ng version

This command will display the version of Angular, TypeScript, and other packages used in your project.

TypeScript Compiler
Another way to check the TypeScript version is to use the TypeScript compiler. Open your terminal and run the following command in the root directory of your Angular project:
tsc --version

This command will display the version of TypeScript installed on your machine. If the version displayed matches the version specified in the package.json file, that is the version used in your Angular project.

The following table summarizes version compatibility between Angular, TypeScript, and Node.

In conclusion, identifying the TypeScript version in an Angular project is important when developing large-scale applications. You can check the version of TypeScript using the package.json file, Angular CLI, or TypeScript compiler. Once you have identified the TypeScript version, you can use it to ensure that your code is compatible with the specific version of TypeScript being used in your Angular project.



AngularJS Hosting Europe - HostForLIFE :: How To Prevent XSS(Cross Site Scripting) Attacks In Angular?

clock March 9, 2023 08:08 by author Peter

Hello, here we are going to discuss how to prevent XSS attacks or Cross-Site Scripting in angular applications.

When we make any web application, then security is an important part of an application where we need to secure our web application from various attacks, one of which is an XSS attack or cross-site scripting attack.

What is XSS(Cross-Site Scripting)
XSS is a kind of injection attack. Let’s consider you have an application, and that application contains the contact form or registration form, where the user enters either their queries or their information in the input field or text Area field.

For example, what happens if a hacker gives a malicious script injected in the contact form text are Like the below script and clicks on submit
<script>alert(“XSS Attack");"</script>

Now, in this case, it will open a popup, and behind the screen, the website will send the request to the hacker’s computer with the current system cookies information or your crucial information will be in the attacker's system, even if you will not even realize it that XSS attack is happening.

Generally, an XSS attack happens on DOM elements (Object data model), like input, and text area Fields, so to prevent our website from an XSS attack we need to check whether the request contains the script or not, and if it contains then we need to handle such kind of condition.

How to prevent XSS attacks in Angular?

When we create an angular application then there is also a chance to happen an XSS attack, so let’s understand it with an example.

XSS Escaping/bypass security in Angular
To prevent cross-site scripting (XSS) attacks in the angular application, we can use the built-in angular cross-site scripting (XSS) protection.

This is enabled automatically by the angular CLI.

Now let’s create an angular application and write the below code in app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Angular15Service } from './angular15.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular 15 App';
    username = '';
    constructor() {}
    ngOnInit() {}
}


And write the below code in app.component.html
<p >{{title}}</p>
<label for="username">Name: </label>
<textarea id="username" [(ngModel)]="username" placeholder="Name"> </textarea>
<p>{{ username }}</p>

Here we can see, we are using Two-way data binding.

So when we give any value to the text area field, the same value we are printing in the paragraph using “interpolation”

When we are running the above code and give any value in TextArea then interpolation will not able to take input as HTML and display the full input as the plain text on your web application page, this mechanism is generally called “contextual escaping” like below
<script>alert(“XSS Attack");"</script>

Angular Input Sanitization
Now let’s take another example, not instead of taking username value instead of using interpolation, here we use innerHTML.

So now let’s change the HTML code like below
<p >{{title}}</p>
<label for="username">Name: </label>
<textarea id="username" [(ngModel)]="username" placeholder="Name"> </textarea>
<p [innerHTML]="username"></p>

Now let’s run your application and see the output, unlike the interpolation, [innerHTML] also shows the text Area input value.

If you give input values as <script> format in the text area like below
<script>alert(“XSS Attack");"</script>

You will see [InnerHTML] automatically understand the <script> tag as the unsafe tag and remove it and don’t print it like below, this is called “sanitization” in Angular.

After entering the above script, you see the inspect element, which shows

So in angular unlike [innerHTML], angular has another tag like [style], [href] as well which recognizes the <script> tag.

Sanitization function in Angular

Another way to prevent the XSS attack, we can use an angular build-in function called sanitization function like the bypassSecurityTrustHtml() function.

So to sanitize the <script> tag to the page, below is the example

Below is the app.component.html
<p >{{title}}</p>
<p [innerHTML]="username"></p>

Below is the app.component.ts code
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Angular15Service } from './angular15.service';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'angular 15 App';
    username = '';
    constructor() {}
    ngOnInit() {}
}


Here we have a taken username object type of SafeHtml, it is a marker interface that gives security to the web applications from untrusted script execution on the browser.

DomSanitizer is used to sanitize the DOM element.

When you run the above code, it contains <script> tag hence we can see on the browser it doesn’t print it on the browser.

So if you are working with the angular application, it automatically secures the angular application from an XSS attack.



AngularJS Hosting Europe - HostForLIFE :: How To Create Password And Confirm Password Matching Validation In Angular?

clock February 17, 2023 08:34 by author Peter

In this article, we will learn how to create a password and confirm password matching validation in an Angular application. Password and confirm password matching validation is generally required in the registration form and password reset or create form.

Prerequisites
    Basic knowledge of Angular
    Visual Studio Code
    Node and NPM installed
    Bootstrap

For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:

Create an Angular Project
Let's create a new angular project by using the following command.
ng new PassValidationExample

Open a project in Visual Studio Code using the following commands.
cd PassValidationExample
Code .


Now in Visual Studio, your project looks as below.

 

 

 

For validation, we need to import Validators from  '@angular/forms'
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

App.component.html
<div class="container">

    <div style="margin: 30px">
        <h1 class="ion-text-center">Register</h1>

        <form [formGroup]="loginForm">
            <div class="form-group">
                <label>First Name*</label>
                <input class="form-control" formControlName="fname" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.fname">
                    <div class="error-message" *ngIf="loginForm.get('fname').hasError(error.type) && (loginForm.get('fname').dirty || loginForm.get('fname').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Last Name*</label>
                <input class="form-control" formControlName="lname" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.lname">
                    <div class="error-message" *ngIf="loginForm.get('lname').hasError(error.type) && (loginForm.get('lname').dirty || loginForm.get('lname').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Email Id*</label>
                <input class="form-control" formControlName="email" type="text" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.email">
                    <div class="error-message" *ngIf="loginForm.get('email').hasError(error.type) &&
    (loginForm.get('email').dirty || loginForm.get('email').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Password*</label>
                <input class="form-control" formControlName="password" type="password" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.password">
                    <div class="error-message" *ngIf="loginForm.get('password').hasError(error.type) && (loginForm.get('password').dirty || loginForm.get('password').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>

            <div class="form-group">
                <label>Confirm Password*</label>
                <input class="form-control" formControlName="confirmpassword" type="password" />
            </div>
            <div class="error-messages">
                <ng-container *ngFor="let error of error_messages.confirmpassword">
                    <div class="error-message" *ngIf="loginForm.get('confirmpassword').hasError(error.type) && (loginForm.get('confirmpassword').dirty || loginForm.get('confirmpassword').touched)">
                        {{ error.message }}
                    </div>
                </ng-container>
            </div>
      <pre>
        Form Error - {{ loginForm.errors | json }}
      </pre>
            <button class="form-control btn btn-primary" [disabled]="!loginForm.valid">Signup</button>
        </form>
    </div>
</div>


App.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  loginForm: FormGroup;

  error_messages = {
    'fname': [
      { type: 'required', message: 'First Name is required.' },
    ],

    'lname': [
      { type: 'required', message: 'Last Name is required.' }
    ],

    'email': [
      { type: 'required', message: 'Email is required.' },
      { type: 'minlength', message: 'Email length.' },
      { type: 'maxlength', message: 'Email length.' },
      { type: 'required', message: 'please enter a valid email address.' }
    ],

    'password': [
      { type: 'required', message: 'password is required.' },
      { type: 'minlength', message: 'password length.' },
      { type: 'maxlength', message: 'password length.' }
    ],
    'confirmpassword': [
      { type: 'required', message: 'password is required.' },
      { type: 'minlength', message: 'password length.' },
      { type: 'maxlength', message: 'password length.' }
    ],
  }

  constructor(
    public formBuilder: FormBuilder
  ) {
    this.loginForm = this.formBuilder.group({
      fname: new FormControl('', Validators.compose([
        Validators.required
      ])),
      lname: new FormControl('', Validators.compose([
        Validators.required
      ])),
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
      password: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
      confirmpassword: new FormControl('', Validators.compose([
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(30)
      ])),
    }, {
      validators: this.password.bind(this)
    });
  }

  ngOnInit() {
  }

  password(formGroup: FormGroup) {
    const { value: password } = formGroup.get('password');
    const { value: confirmPassword } = formGroup.get('confirmpassword');
    return password === confirmPassword ? null : { passwordNotMatch: true };
  }

}


App.component.css
p {
  font-family: Lato;
}
.error-message {
  color: red;
}
input.ng-touched.ng-invalid {
  border: 1px solid red;
}

Now run the project using the following command
npm start

In this article, I have discussed the implementation of password and confirm password matching validation in Angular application.



AngularJS Hosting Europe - HostForLIFE :: How To Create A Download Progress Bar With Angular And Material Design?

clock December 20, 2022 07:03 by author Peter

To create a download progress bar with a percentage in Angular, you can use the HttpClient module to request a server and track the download's progress. Here is an example of how this can be done,
    First, install the @angular/material and @angular/cdk packages in your Angular project:
    npm install @angular/material @angular/cdk


Import the MatProgressBarModule and MatProgressSpinnerModule modules from the @angular/material package in your Angular module:
import { MatProgressBarModule, MatProgressSpinnerModule } from '@angular/material';

@NgModule({
  imports: [
    MatProgressBarModule,
    MatProgressSpinnerModule
  ],
  // ...
})
export class AppModule { }


Now, import the HttpClient module and the HttpEventType enum from the @angular/common/http package:
import { HttpClient, HttpEventType } from '@angular/common/http';

Inject the HttpClient service into your component or service using the constructor:
constructor(private http: HttpClient) {}

Create a function to make the download request and track the progress:
public percentDone: number = 0;

public downloadFile() {
  this.http.get('https://example.com/file.zip', { responseType: 'blob' })
    .subscribe(event => {
      if (event.type === HttpEventType.DownloadProgress) {
        // Update the progress bar with the download percentage
        const this.percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`Downloaded ${this.percentDone}%`);
      } else if (event.type === HttpEventType.Response) {
        // Save the downloaded file
        const file = new Blob([event.body], { type: 'application/zip' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      }
    });
}


In your component's template, use the mat-progress-bar and mat-progress-spinner components to display the progress bar and percentage:
<mat-progress-bar mode="determinate" [value]="percentDone"></mat-progress-bar>
<mat-progress-spinner mode="determinate" [value]="percentDone"></mat-progress-spinner>
<p>{{percentDone}}%</p>

You can use the percentDone property to bind to the value attribute of the mat-progress-bar and mat-progress-spinner components, as well as to display the percentage as text.

This is an example of how you can create a material design download progress bar with a percentage in Angular. You can customize the appearance and behaviour of the progress bar and percentage by using the various options and styles available for the mat-progress-bar and mat-progress-spinner components.



AngularJS Hosting Europe - HostForLIFE :: Create Your First Angular 15 Application

clock December 6, 2022 07:00 by author Peter

We know Angular 15 is released on November 2022, so now in this article, we will see how to create an Angular 15 project. If you have already worked with angular previously you know, angular CLI helps us to build an angular application. Creating a new project in angular is now as simple as installing the Angular CLI and running the ng new command.


What is Angular CLI?
The Angular CLI helps us to create an Angular application and it uses Typescript, it creates an angular application with all the configuration files and the packages in one single command.

It helps us to add features (components, pipe, services, directives, etc.) to existing or new Angular applications.

How to create a new Angular 15 project

To create a new angular 15 project, first we need to set up the system environment

Installing Visual Studio Code
We need an editor to create the application so for that we need to install VS code. It is easy to install and helps us to create an angular application easily. You can download Visual Studio Code from the following link.

Node.Js

Node.js is the open source, cross-platform javascript run time environment.

Go to https://nodejs.org/en/

And install the LTS version
Install the Package Manager

To install Angular and its dependencies, we now need to install Node Package Manager (NPM).

NPM is the node.js package manager for JavaScript, which is automatically installed when we install node.js.

To see the version of NPM, run the below command on the Node.js command prompt like below
Node -v

Go to the Node.js command prompt and install typescript using the below command
Npminstall –gTypescript
Angular CLI (command line interface)

It is a tool that allows us to create a project using the command line argument.

So below is the command to create the latest angular project
npminstall -g @angular/cli@latest

Once the above command runs successfully, now check the latest version of angular and run the below command
Ngversion

Since I was already working on angular 14, so for me only I need to run the Angular CLI command.
Below is the image when my angular version is v14,

Now I ran below CLI command and then check the angular version like the below image
npminstall -g @angular/cli@latest

So this is the way we can upgrade the angular version to the latest version. You can also install the older version of Angular as shown below,

    MDAngular8
    cdAngular8
    npmi @angular/[email protected]

Now to create an Angular 15 application run the below command
NgnewAngular15App

Once you run the above command it will ask to install routing like below, give Y and press enter

After that, it will ask to add CSS like the below,

Once you press enter, it will take a few minutes to create the Angular 15 Application.

So from above, we can see, the angular 15 project creation is in progress.

From the above image, we can see, the angular 15 projects was created successfully. After creating this project, now let's open the VS code, go File tab then select the folder, and go to the directory where we created the angular 15 project, from there, select the angular15 project folder. Once you will load the project, you will see all files in VS code.

Now run the ng serve –o command, it will open the angular15 project like below

 

If you face an error like below then delete ng.ps1 file
PS C:\Users\DELL\Angular15App> ng serve -o

ng : File C:\Users\DELL\AppData\Roaming\npm\ng.ps1 cannot be loaded. The file C:\Users\DELL\AppData\Roaming\npm\ng.ps1 is not digitally signed.
You cannot run this script on the current system. For more information about running scripts and setting execution policies, see
about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

Then follow the below points then run ng serve –o again,
    Delete ng.ps1 from the directory C:\Users\% usernam%\AppData\Roaming\npm\
    Try to clear the npm cache directory C:\Users\%usernam%\AppData\ Roaming\npm-cache\

Note - Sometimes without clearing the cache also, the above error is resolved.
Now to verify that this application is created in Angular15, just go to the package.json file and see all the libraries are in v15 like below.

To build the application below is the command
ng build

To run the application below is the command
ng serve

after serving the application, go to the browser and enter the below URL, this is the default URL where the angular application run.
http://localhost:4200/



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