Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: What Is Interceptor In Angular And Use Cases Of Interceptor?

clock March 31, 2023 07:36 by author Peter

In Angular, an interceptor is a middleware service that can intercept HTTP requests and responses from the application to the server. The interceptor can modify the requests or responses, add headers or tokens, handle errors, or perform any other necessary actions.


Interceptors are defined as services in Angular, and they can be added to the application by providing them in the HTTP_INTERCEPTORS multi-provider token.

Here's an example of an interceptor that adds an authorization token to every outgoing HTTP request:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const token = localStorage.getItem('auth_token');
    if (token) {
      const authRequest = request.clone({
        headers: request.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(authRequest);
    }
    return next.handle(request);
  }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and provides the intercept() method. The intercept() method receives the incoming request and the HttpHandler object that allows us to pass the request to the next interceptor or the final HTTP handler.

The method first checks if an authorization token is present in the local storage. If the token is present, the method creates a new request with an additional Authorization header that includes the token. If the token is absent, the method passes the original request to the next handler.

To use this interceptor in your application, you need to provide it in the HTTP_INTERCEPTORS multi-provider token. Here's an example of how to do this:
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';

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


In this example, the AuthInterceptor is provided in the HTTP_INTERCEPTORS token as a multi-provider, which means that it can be combined with other interceptors if needed.

Interceptors in Angular have several use cases:

  • Authentication and authorization: You can use an interceptor to add authentication tokens or authorization headers to outgoing requests. This helps ensure that only authorized users can access protected resources.
  • Error handling: You can use an interceptor to handle errors that occur during HTTP requests. This can be useful for handling network, timeouts, or server-side errors.
  • Caching: You can use an interceptor to cache responses from the server, which can improve the performance of your application.
  • Logging: You can use an interceptor to log HTTP requests and responses. This can be useful for debugging and monitoring your application's performance.
  • Transformation of requests and responses: You can use an interceptor to modify the request or response data. This can be useful for adding or removing data or transforming data to match the format your application expects.

Overall, interceptors are a powerful feature of Angular that can help you improve your application's performance, security, and reliability. By using interceptors, you can centralize common functionality that needs to be applied to all HTTP requests and keep your code clean and modular.

Interceptors were introduced in Angular version 4.3.0 and are available in all subsequent versions. So, if you use Angular 4.3.0 or later, you can take advantage of the interceptor feature.

Note that interceptors are part of the @angular/common/http module, so you must import this module into your application to use interceptors. If you are using an earlier version of Angular that does not support interceptors, you can consider upgrading your application to a newer version of Angular to take advantage of this feature.

I hope this helps. If this helps you, then share it with others.

Sharing is caring! :)



AngularJS Hosting Europe - HostForLIFE :: Angular 15 – What’s New and Why to Upgrade?

clock March 27, 2023 08:16 by author Peter

As we know, Google has released a new version of Angular i.e. Angular 15 recently. As per the expectation, the Angular team majorly focussed on the stability and performance improvement of the framework. So, in this article, we will discuss the new features introduced in Angular 15 and also discuss how to upgrade any existing applications to Angular 15.  Angular 15 is released on November 16, 2022. As we already mentioned, this version mainly contains many features related to the performance and stability of the application.

What is New in Angular 15?
The Client-Side Web-based application development process changed a lot once the Angular team introduced the new versions of Angular a few years back. All the current versions of Angular are based on TypeScript languages and are open-source-based frameworks. As developers, we can use develop any client-based SPA or Single-Page Application very easily with the help of Angular. On November 2022, Google released the new version of the Angular framework, i.e. Angular 15. Angular 15 is released with many stable standalone API supports which helps developers to bootstrap any web application by using a single component. As we know, the previous version Angular 14 is the most feature-based release by the Angular team and it also supports the latest TypeScript version i.e. TypeScript 4.7. As per the earlier release, the Angular team also declared that by removal of Angular’s Legacy Compiler and the rendering pipeline in the past releases, improves the performance of the application along with the developer’s experience.

Some of the key functionalities and features included in the Angular 15 are as follows –
    Standalone Stable APIs
    Directive Composition API
    Improve Stack Traces for Debugging
    Http with provideHttpClient
    Stable Image Directives
    Dependency Injection
    Functional Route Guards
    Automatic Imports in Language Service
    Angular CLI improvements
    CDK Based Listbox

With the latest release of Angular 15, we can use the single component concepts in Router, Angular Element, HttpClient, and other areas. So, if we use the Standalone Component, then it makes the development process much easier and also can provide us with an alternative way of using ngModule. So, the developer can develop any application without the ngModules which reduces the unnecessary complex design of any application.

Different Characteristics of Angular 15
So, while we discuss the Angular 15-related new characteristics or features, we should understand the changes done in Angular 15 compared to the previous versions of Angular Framework. Through this article, our primary focus is to discuss related the key features or characterize of the Angular frameworks. So, as a Framework, Angular 15 has many more features than those mentioned in this article. But, here, we only focus on some key or important features related to Angular 15 with this article.

01. Stable Standalone API
At the time of the Angular 14 version release, the Angular team officially announced that they are going to remove Angular’s legacy compiler and rendering pipeline implementation to improve the developer experience and performance. For the same purpose, in Angular 14 they release the Developer Preview version of Angular Standalone API. With the help of this, developers can develop any application without defining any Ng Modules. That, also helps us to create an app with less boilerplate code which improve the performance of the applications. Now, in Angular 15, Angular Standalone API is released as a stable version as it is now graduated from the preview version.  The standalone API is not fully functional in many areas of angular framework like HttpClient, Angular Router, Elements, and many more. Now, in Angular 15, we can directly bootstrapping any application through a single component with the help of a Standalone API.
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { AppComponent } from'./app.component';

@Component({
    standalone: true,
    selector: 'sample-component',
    imports: [ AppComponent ],
    template: `<h1>Welcome to Angular 15</h1>`,
})
export class SampleComponent {

    // component logic
}

bootstrapApplication(SampleComponent);


As per the above example, we can use the reference of the Standalone directives or components or pipes under the import function. If we mark the component as a “standalone: true” the under the component metadata, then we do not need to declare or use that component within NgModules. Also, if we require to use any specific module within the standalone component, then we can use the import function to import that module directly within that function like “import : [module_name]”.

02. Directive Composition API
Directive Composition API is one of the new features introduced in the Angular 15 release. This feature is introduced in Angular 15 due to the popular feature request on GitHub by the developer community. With the help of this, we can reuse our code. Directive Composition API helps developers to use host elements with the existing directives and in this way, it helps us to implement code reusability functionality within the application. This feature also helps developer to save time during the development process. While we use directive composition API, that particular directive acts as a Standalone directive. It needs to be remembered that all the functionality related to the directory composition API is possible with the help of the Angular compiler.
import { Component } from '@angular/core';

@Component({
    selector: 'app-menu',
    hostDirectives: [
        HasColor,
        {
            directive: CdkMenu,
            inputs: ['cdkMenuDisabled: disabled'],
            outputs: ['cdkMenuClosed: closed']
        }
    ]
   })
class AppMenu {
}


In the above example, we can see AppMenu Component is created with the help of two different hostDirectives i.e. HasColor and CdkMenu. Due to this technical enhancement in Angular 15, we can reuse the properties of any existing directives. Here as per the example, the AppMenu component will inherit all the input, and output properties along with the business logic of HasColor Directive and input, and for CdkMenu, it will inherit the input properties and the business logic.

03. Image Directive
The concept of Image Directive (or NgOptimized Image) is first introduced in Angular 14 along with Chrome Aurora to improve the performance of image loading. After that release, developers experience around 75% of improvement in the LCP. Now, in Angular 15, the same Image directives become much more stable along with some new features. Now, in this directive, we can take benefit of the automatic generation functionality of the SRC set. It helps us to upload and return the appropriate size of the images whenever we require. Due to this, the download time of the image is reduced. Also, we can use another feature called Fill Mode (currently it is released as an experimental mode). With the help of this, we do not need to declare the image dimensions. It is quite helpful when we try to migrate the CSS-based background image to use this directive or when we don’t know the exact dimension of the image.

This directive, i.e. NgOptimized can be used directly either in the NgModule.
import { NgOptimizedImage } from '@angular/common';

// Include it in the necessary NgModule
@NgModule({
  imports: [NgOptimizedImage],
})
class AppModule {}


Also, we can use it within the Angular component directly. While we need to use the Angular Image directives within a component, we need to replace the src attribute of the image tag with ngSrc, so that the image directive can prioritize the attribute to optimize the speed of the LCP images.
import { NgOptimizedImage } from '@angular/common';

@Component({
  standalone: true
  imports: [NgOptimizedImage],
})
class MyComponent {}


04. Functional Route Concept
The angular team introduced a new concept in the implementation process of route guards in Angular 15. In the earlier version, we normally use the class-based implementation for the route guards. But now in Angular 15, it is marked as @deprecated as per the Angular documentation. A new approach called Functional Route Guards has been introduced in place of the class-based approach. By using the new approach, we need to define the functions in place of the class-based concept while defining route guards and it helps us to implement route guards in a much more efficient and streamlined way. For this purpose, we can use the inject function from the @angular/core package which helps us with the dependency injection. This implementation helps us to create a reusable and composable function that we can pass as an argument within the Angular Router’s canActivate or canActivateChild functions.

As per the Angular documentation, the benefits of the functional route guards are as follows –
    We can define the route guards and their resolvers as a JavaScript functions as well.
    It reduced the boilerplate code as functional route guards do not require to define different guard class definitions.
    Functional route guards increase flexibility as they can be defined as an inline function also.
    Performance wise functional route guards are faster as compared to class-based guards. It is because it does not require creating or initiating the separate class objects instance.

05. Http with provideHttpClient
One of the new improvements in Angular 15 is that we can now use the provideHttpClient option to use HttpClient in place of using HttpClientModule. As we know that in Angular 15, modules are becoming optional now. So, in that case, taking the support of the HTTP module is a stress. So, now we can use use the provideHttpClient() which offers the support of the HttpClient.

06. Language Service
Now, in Angular 15, we can import such components directly with the help of language services that are not either mentioned as a standalone component or within the NgModules. Now angular in-language support service provides an option called Quick Fix. Through this, we can write down our angular code much more confidently and we can use this automatic import component and its fixes in the template.

07. Dependency Injection
In Angular 15, there are some changes done in the case of Dependency Injection. They are –

  • In the case of the @Injectable() decorator, it is no more supported with the provided: _NgModule syntax. In this case, we need to use providedIn : “root”.
  • We can also use the NgModule.providers if we want to limit the dependency injection to a single NgModule.
  • Also, the syntax provided: ‘any’ is also deprecated in Angular 15.

08. Improved Stack Trace
Now, in Angular 15 we can take benefit of the better Stack Traces which help us to identify any error or the location of any error. This feature is developers for to debug any issue during the development process. Now, during the execution of any application if an error occurred, then Angular will show the development code along with the library or packages which it calls. In the earlier version, developers faced difficulties to understand the error snippers as –

  • Most of the error message-related information is generated from third-party dependencies like Angular framework, zone.js, and Rx.js.
  • Also, the error message does not provide any information about which line or block code encountered this error.

But now, after a long time of collaboration between the Angular and Google Chrome DevTool team, they integrate those third-party libraries with the help of node_modules, zone.js, etc to raise proper error messages by using stack trace. So, now through this error message information, the developer can easily identify the exact code block of that error and fix it quickly.

09. MDC-based Components
With the release of Angular 15, we can use the much more stable Angular material-based components. Now, most of the Angular material components s designed in such a way that we can use them in web applications as well. Most of the changes regarding these components are based on DOM and CSS related. Now, in Angular 15, many Angular Material components related to old implementations have been deprecated or moved to the legacy section. So, if we still want to use them then we need to use the “legacy” import option for that.
import {MatLegacyButtonModule} from '@angular/material/legacy-button';

10. Improved ES-Build Supports
In the Angular 14 release, the Angular team announced one experimental functionality support called esBuild support to enable the faster build time of the application. Now, with Angular 15, the same esBuild support is extended with some new functionality like SVG template, and file replacement. Now, it also supports the ng build –watch command. The command for upgrading the angular.json builder is:-
"builder": "@angular-devkit/build-angular:browser-esbuild",

How to Upgrade to Angular 15?
So, in the above section, we have discussed the new functionality and features of Angular 15. Now, let's discuss how we can upgrade any existing angular application to the Angular 15 version. Before going to upgrade to Angular 15, we need to know some dependencies related to Angular 15 like –

  • Angular 15 has provided support for node.js version 14.20.x, 16.13.x and 18.10.x. And it terminates the support related to version 14.[15-19].x and 16[10-12].x.
  • Angular 15 now only support TypeScript version 4.8 or older than that.


So, we can use the below commands to update Angular 14 to Angular 15 –
ng update @angular/cli @angular/core

Conclusion
This article discusses some key functionalities of Angular 15. As Angular team is majorly focusing on the performance improvement of the framework for this version like server-side rendering, code reusability, etc. This type of improvement always helps the easier learning curve more simplified. So, let's upgrade the application to the Angular 15 version and use its new features and functionality of it.



AngularJS Hosting Europe - HostForLIFE :: Procedural Vs Declarative Approach In RxJS

clock March 20, 2023 09:36 by author Peter

RxJS has two main approaches to handling asynchronous data streams: procedural and declarative.


I have used the below tools to prepare this tutorial.
    Angular CLI - 15.1.6
    Node: 18.14.0
    NPM – 9.3.1
    Visual Studio Code

Procedural programming involves using imperative code to handle asynchronous operations, such as making HTTP requests and updating the UI. Procedural code typically involves chaining together methods and callbacks to create a sequence of steps that must be executed in a specific order. Procedural code can be challenging to read, understand, and maintain, especially as the codebase grows.

Sample code snippet for Procedural Approach,
// All users
getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.userUrl).pipe(
    catchError(this.handleError)
  );
}


The code defines a function called getUsers() that returns an Observable of an array of User objects. Overall, this code defines a procedure in Angular to retrieve a list of users from a specific URL using the HttpClient and handle any errors that may occur during the HTTP request.

On the other hand, declarative programming involves using a functional approach to handle asynchronous data streams. With declarative programming, you create Observables that emit data and use operators to transform, filter, and combine these data streams. Declarative code is typically easier to read and understand and can be more modular and reusable.

Code snippet for Declarative Approach,
/All Users
users$ =this.http.get<User[]>(this.userUrl).pipe(
    catchError(this.handleError)
)


The code defines a property called users$ using the declarative approach in Angular.

The $ symbol at the end of the property name is a convention used in Angular to indicate that the property is Observable. The property is being initialized with the result of an HTTP GET request made using the HttpClient. The request is made to this.userUrl URL and expects to receive an array of User objects in the response. Overall, this code uses the declarative approach in Angular to define an Observable property that retrieves a list of users from a specific URL using the HttpClient.

In Angular, the declarative approach to RxJS is generally preferred over the procedural approach. Angular provides many built-in directives and pipes that allow you to use declarative code to handle common use cases, such as displaying data from an HTTP request or handling user input.



AngularJS Hosting Europe - HostForLIFE :: TypeScript Versions In Angular Validation In Angular Reactive Form

clock March 17, 2023 08:06 by author Peter

Angular Reactive forms are an essential part of building modern web applications. These forms allow for a more streamlined approach to managing data input and validation, and they are highly customizable. In this blog post, we will explore how to create an Angular Reactive form with display validation.

Prerequisites
You should have a basic understanding of Angular and Reactive Forms. If you're unfamiliar with these topics, you can check out the official Angular documentation at the portal.

The source code can be downloaded from GitHub

I have used the below tools to prepare this tutorial.
    Angular CLI - 15.1.6
    Node: 18.14.0
    NPM – 9.3.1
    Visual Studio Code

To get started, let's assume we have a simple form that collects basic user information like name, email, and phone number. We'll create a FormGroup in our component to hold our form controls and validators:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl, AbstractControl } from '@angular/forms';

@Component({
    selector: 'app-user-form',
    templateUrl: './userform.component.html',
    styleUrls: ['./userform.component.scss']
})
export class UserformComponent implements OnInit {
    userform: FormGroup = new FormGroup({
        name: new FormControl(''),
        email: new FormControl(''),
        phone: new FormControl('')
    });
    submitted = false;
    constructor(private fb: FormBuilder) {}
    ngOnInit(): void {
        this.userform = this.fb.group({
            name: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            phone: ['', [Validators.required, Validators.minLength(10)]]
        });
    }
    get f(): {
        [key: string]: AbstractControl
    } {
        return this.userform.controls;
    }
    onSubmit(): void {
        this.submitted = true;
        if (this.userform.invalid) {
            return;
        }
        console.log(JSON.stringify(this.userform.value, null, 2));
    }
}

We're using the FormBuilder service to create our form controls and validators. The name control is required, the email control is required and must be a valid email address, and the phone control is required and must be at least 10 digits long.

Now that we have our form set up, we can use it in our template:
<div class="register-form">
<form  (ngSubmit)="onSubmit()" [formGroup]="userform">
    <div class="form-group">
      <label>Name:</label>
      <input type="text" formControlName="name"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['name'].errors }"
      >
      <div *ngIf="submitted && f['name'].errors" class="invalid-feedback">
        <div *ngIf="f['name'].errors['required']">
          Name is required
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Email:</label>
      <input type="email" formControlName="email"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['email'].errors }"
      >
      <div *ngIf="submitted && f['email'].errors" class="invalid-feedback">
        <div *ngIf="f['email'].errors['required']">
          Email is required
        </div>
        <div *ngIf="f['email'].errors['email']">
          Email is not valid
        </div>
      </div>
    </div>

    <div class="form-group">
      <label>Phone:</label>
      <input type="tel" formControlName="phone"
      class="form-control"
      [ngClass]="{ 'is-invalid': submitted && f['phone'].errors }"
      minlength="10" maxlength="11">
      <div *ngIf="submitted && f['phone'].errors" class="invalid-feedback">
        <div *ngIf="f['phone'].errors['required']">
              Phone is required
        </div>
            <div *ngIf="f['phone'].errors['minlength']">
              Phone must be at least 10 digits
            </div>
        </div>
    </div>
    <div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
  </div>
  </form>
</div>

In our template, we bind our formGroup to the userForm property in our component. We're also using the formControlName directive to bind each input field to its respective control.

We display validation messages for each control using Angular's *ngIf directive. We're checking if the control is invalid and either dirty or touched. If it is, we're displaying the relevant error message. For example, if the name control is required and the user has not entered anything, we'll display the "Name is required" error message.

We're also disabling the submit button if the form is invalid, which means validation errors are present.

Now that we have our form set up and displaying validation messages, we must handle form submission in our component. We'll create an onSubmit() method that will log the form data to the console:
onSubmit(): void {
    this.submitted = true;
    if (this.userform.invalid) {
        return;
    }
    console.log(JSON.stringify(this.userform.value, null, 2));
}

The sample screenshot is given below.


And that's it! We've created an Angular Reactive form with display validation with just a few lines of code. This form is highly customizable and can be expanded to collect more complex data easily.

With the assistance of ChatGPT, I am thrilled to have completed my third blog post.



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 :: Create Registration Form In Angular 14

clock March 3, 2023 09:52 by author Peter

This blog teaches how to create a registration form in Angular 14. Here's a basic example,


1. Create a new Angular component for your registration form. In the command line, run ng generate component registration-form.

2. Open the registration-form.component.html file and add the following code,
<form (ngSubmit)="onSubmit()">
  <label> Name: <input type="text" [(ngModel)]="name" name="name" required>
  </label>
  <br>
  <label> Email: <input type="email" [(ngModel)]="email" name="email" required>
  </label>
  <br>
  <label> Password: <input type="password" [(ngModel)]="password" name="password" required>
  </label>
  <br>
  <button type="submit">Submit</button>
</form>


3. Open the registration-form.component.ts file and add the following code:
import { Component } from '@angular/core';

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.css']
})
export class RegistrationFormComponent {
  name: string;
  email: string;
  password: string;

  onSubmit() {
    console.log('Registration form submitted!');
    console.log(`Name: ${this.name}`);
    console.log(`Email: ${this.email}`);
    console.log(`Password: ${this.password}`);
  }
}


4. Save your changes and run ng serve to start the development server.
5. Open your browser and navigate to http://localhost:4200/registration-form. You should see the registration form displayed on the page.
6. Enter your name, email, and password into the form fields and click the Submit button. You should see the form data logged to the console.

Note that this is just a basic example, and you'll want to add more validation and error handling to your form in a real-world application. You may also want to store the user's registration data in a database or send it to a server via an HTTP request.



AngularJS Hosting Europe - HostForLIFE :: Angular Reactive Forms With Validation Example

clock March 1, 2023 07:08 by author Peter

First, you need to import the required modules in your component:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';


Then, you can create the form using the FormBuilder service:
@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      message: ['', Validators.required]
    });
  }
}


In this example, the myForm property holds the reactive form instance. The createForm method uses the FormBuilder service to create the form and define its fields with initial values and validators. The name field is required, the email field is required and must be a valid email address, and the message field is required.

Now, you can use this form in your template:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <label for="name">Name:</label>
  <input type="text" id="name" formControlName="name">
  <div *ngIf="myForm.get('name').invalid && (myForm.get('name').dirty || myForm.get('name').touched)">
    <div *ngIf="myForm.get('name').errors.required">Name is required.</div>
  </div>

  <label for="email">Email:</label>
  <input type="email" id="email" formControlName="email">
  <div *ngIf="myForm.get('email').invalid && (myForm.get('email').dirty || myForm.get('email').touched)">
    <div *ngIf="myForm.get('email').errors.required">Email is required.</div>
    <div *ngIf="myForm.get('email').errors.email">Invalid email format.</div>
  </div>

  <label for="message">Message:</label>
  <textarea id="message" formControlName="message"></textarea>
  <div *ngIf="myForm.get('message').invalid && (myForm.get('message').dirty || myForm.get('message').touched)">
    <div *ngIf="myForm.get('message').errors.required">Message is required.</div>
  </div>

  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>


In this example, the formGroup directive binds the myForm instance to the form element. The formControlName directive binds each form control to the corresponding field in the myForm instance. The *ngIf directives display error messages for each field if it's invalid and has been touched or is dirty.

Finally, you can handle the form submission in your component:
onSubmit() {
  // Do something with the form data
}


This is a basic example, but you can add more validation rules and custom validators as needed.



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