Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Angular v16 is available | Angular 16 new feature | What's New in #Angular16

Angular v16 has released in May 2023; in this article, we will discuss new features introduced in angular v16

Last year Angular 15 was released in November 2022 with some new features, including performance improvement and standalone components and API. So now (May 2023), Angular V16 has been released with some new features and enhancements.

Angular v16

Please follow the below link for more,

  1. Angular 14 Features
  2. Angular 15 Features

Angular 16 new features

  1. Rethinking Reactivity
  2. Angular Signals
  3. RxJS interoperability
  4. Server-side rendering 
  5. hydration enhanced
  6. Improved tooling experience for standalone components, pipes, and directives
  7. Advancing developer tooling
  8. Better unit testing using Jest and Web Test Runner
  9.  Autocomplete imports within the HTML templates.      

Rethinking Reactivity

  1. It helps us to improve the performance and the developer experience.
  2. It completely depends on backward compatibility and the inoperable with the current system and then enabling it.
  3. It improves performance by reducing the number of the computation during the change detection.
  4. It enables fine-grained reactivity

Angular Signals

Now just like the signals we used in React, it is available in Angular V16 as well.

This signal library allows us to define all the reactive values and then expose their dependencies.

@Component({
  selector: 'my-app',
  standalone: true,
  template: `
    {{ fullName() }} <button (click)="DisplayName('DotNet')">Click</button>
  `,
})
export class App {
  fName = signal('DotNet_new');
  lName = signal('Office');
  fullName = computed(() => `${this.fName()} ${this.lName()}`);

  constructor() {
    effect(() => console.log('Name :', this.fullName()));
  }

  DisplayName(name: string) {
    this.firstName.set(name);
  }
}
ASP.NET (C#)

In the above code, we are computing the value of fullName, which depends on the signals fName and the LName. Here we declare an effect, which executes every time we make changes in the value of any of the signals.

When we give the value off the Name ”dotnet”, it will log into the console.

"Name : dotnet office"
ASP.NET (C#)






RxJS interoperability

Now we will able to use signals in observables using functions by using below CLI command which is still in preview @angular/core/rxjs-interop

Convert observable to signal 

import { signal,toObservable } from '@angular/core/rxjs-interop';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class App {
  count = signal(0);
  count1 = toObservable(this.count);

  ngOnInit() {
    this.count1.subscribe(() => ..);
  }
}
ASP.NET (C#)

Convert Signal to observable

import { signal,toObservable,toSignal } from '@angular/core/rxjs-interop';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: `
  <li *ngFor="let row of data()"> {{ row }} </li>
`,
  styleUrls: ['./app.component.css']
})
export class App {
  dataService = inject(DataService);
  data = toSignal(this.dataService.data$, []);
}
ASP.NET (C#)




Server-side rendering and hydration enhanced

  1.    So the Angular team has done enhancement in performance with the help of the Chrome Aurora team.
  2.   They have improved the server-side rendering.



Reference: https://blog.angular.io/angular-v16-is-here-4d7a28ec680d

---------------------------------

What is Standalone Component in Angular | Standalone Component in Angular 15

Angular is the most popular front-end framework and is used to make web applications, now launched a new version v15 in Nov 2022, which contains a couple of new features.

In this article, we are going to discuss one of the features of the "Standalone component in Angular v15".

The standalone component is basically released with angular V14 with preview mode but it was not stable, but now in v15 it is stable, and we can use it in our application.

What is a Standalone Component?

So when we create any component in the previous version of the angular application, we used to give the reference of that particular component in the app.module.ts (basically in a module file) file in the declaration array, app.module.ts file contains the common feature which is used to perform the operation in a component ( like ngIf,ngFor, etc).

So there is always a dependency in the module, and we always have to remember to give the reference of a component in app.module.ts, and it was an extra layer in an angular application.

So as a beginner we need to extra taken care of such kinds of things, but as angular is growing rapidly and improving a lot, so now V15 has a standalone component means, not no need to define components in the app.module.ts file.

How to create Standalone Components

In the previous version of angular, we used to make components by using the below command

ng g c Student
BASIC

 Or

ng g component Student
BASIC

When we run the above command then it creates the StudentComponent and automatically adds the reference for the same component in the app.module.ts file.




Here we have a component reference in the app.module.ts file hence it’s not a standalone component.

To make a standalone component run the below command

ng g c StudentStandalone --standalone
BASIC

 Here while creating a standalone component we are adding a --standalone in command, and once the component is created, there will not be a reference in the app.module.ts file

And StudentStandalone component looks like below 


In the above image we can see it has 2 new features “standalone: true” and “import:[commonModule]”, so the standalone property tells us that it is not dependent on other modules. The common module basically gives the ability of this component to perform basic operations like *ngIf, *ngFor, etc.

Now standalone can also work in sync with Routers, custom pipes, HTTP clients, angular material, etc.

Even if we want to use a custom pipe, any directive, etc we can directly use them in the Component itself in the import array, not need to give reference in the app.module.ts file.

Even standalone components allow us to make a bootstrap application means when we create an application the main.ts file has the below code

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));
JavaScript

This means from here we bootstrap the application or run the application, here we can see it is adding AppModule in a bootstrap module,  and now we can remove appModule entirely by using the bootstrap application.

So In the main.ts file we can remove the above component and add the below code

bootstrapApplication(AppComponent);


 

And another change that we have to do in Index.html like below


Now when you will run your application and see the output on the default URL (http://localhost:4200/) you will see studentStandalone Component output.



So now there is no dependency on the app.module.ts file and can directly run our standalone component.

Even we can bootstrap an application by defining BootstarpApplication() method.

If you want to see practice implementation for the StandAlone component in Angular 15, please see the below video



------------------------------------------------------------------------------------

How to prevent XSS(Cross Site Scripting) attacks in Angular /Angular15


Hello everyone, 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>
BASIC

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() {}
}
JavaScript

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>
JavaScript

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>
JavaScript

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>
JavaScript

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

WARNING: sanitizing HTML stripped some content, see https://g.co/ng/security#xss



 

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>
JavaScript

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() {}
}
JavaScript

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.










-------------------------------------------------------