Sun. Dec 22nd, 2024
Angular

16. How to inject the dynamic script in angular?

Using DomSanitizer we can inject the dynamic Html,Style,Script,Url.

import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
   selector: 'my-app',
   template: `
       <div [innerHtml]="htmlSnippet"></div>
   `,
})
export class App {
       constructor(protected sanitizer: DomSanitizer) {}
       htmlSnippet: string = this.sanitizer.bypassSecurityTrustScript("<script>safeCode()</script>");
   }

17. What are the security principles in angular?

Below are the list of security principles in angular,

  • You should avoid direct use of the DOM APIs.
  • You should enable Content Security Policy (CSP) and configure your web server to return appropriate CSP HTTP headers.
  • You should Use the offline template compiler.
  • You should Use Server Side XSS protection.
  • You should Use DOM Sanitizer.
  • You should Preventing CSRF or XSRF attacks.

18. What is Angular security model for preventing XSS attacks?

Angular treats all values as untrusted by default. i.e, Angular sanitizes and escapes untrusted values When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation.

19. What is the role of template compiler for prevention of XSS attacks?

The offline template compiler prevents vulnerabilities caused by template injection, and greatly improves application performance. So it is recommended to use offline template compiler in production deployments without dynamically generating any template.

20. What are the various security contexts in Angular?

Angular defines the following security contexts for sanitization,

  • HTML: It is used when interpreting a value as HTML such as binding to innerHtml.
  • Style: It is used when binding CSS into the style property.
  • URL: It is used for URL properties such as
    <div>a href</div>
  • Resource URL: It is a URL that will be loaded and executed as code such as
    <div>script src</div>

21. What is Sanitization? Is angular supports it?

Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. Yes, Angular suppports sanitization. It sanitizes untrusted values for HTML, styles, and URLs but sanitizing resource URLs isn't possible because they contain arbitrary code.

22. What is the purpose of innerHTML?

The innerHtml is a property of HTML-Elements, which allows you to set it's html-content programmatically. Let's display the below html code snippet in a

<div> tag as below using innerHTML binding,

<div [innerHTML]="htmlSnippet"></div>
and define the htmlSnippet property from any component

export class myComponent {
  htmlSnippet: string =  '<b>Hello World</b>, Angular';
}
Unfortunately this property could cause Cross Site Scripting (XSS) security bugs when improperly handled.

23. What is the difference between interpolated content and innerHTML?

The main difference between interpolated and innerHTML code is the behavior of code interpreted. Interpolated content is always escaped i.e, HTML isn't interpreted and the browser displays angle brackets in the element's text content. Where as in innerHTML binding, the content is interpreted i.e, the browser will convert < and > characters as HTMLEntities. For example, the usage in template would be as below,

Interpolated value: <div>{{htmlSnippet}}</div>
Binding of innerHTML: <div [innerHTML]="htmlSnippet"></div>
and the property defined in a component.
export class InnerHtmlBindingComponent {
  htmlSnippet = 'Template  <script>alert("XSS Attack") </script> Code attached';
}
Even though innerHTML binding create a chance of XSS attack, Angular recognizes the value as unsafe and automatically sanitizes it.

24. How do you prevent automatic sanitization?

Sometimes the applications genuinely need to include executable code such as displaying >iframe<from an URL. In this case, you need to prevent automatic sanitization in Angular by saying that you inspected a value, checked how it was generated, and made sure it will always be secure. Basically it involves 2 steps,
Inject DomSanitizer: You can inject DomSanitizer in component as parameter in constructor

Mark the trusted value by calling some of the below methods

  • bypassSecurityTrustHtml
  • bypassSecurityTrustScript
  • bypassSecurityTrustStyle
  • bypassSecurityTrustUrl
  • bypassSecurityTrustResourceUrl

For example,The usage of dangerous url to trusted url would be as below,
constructor(private sanitizer: DomSanitizer) {
  this.dangerousUrl = 'javascript:alert("XSS attack")';
  this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl);

25. Is angular prevents http level vulnerabilities?

Angular has built-in support for preventing http level vulnerabilities such as as cross-site request forgery (CSRF or XSRF) and cross-site script inclusion (XSSI). Even though these vulnerabilities need to be mitigated on server-side, Angular provides helpers to make the integration easier on the client side.

HttpClient supports a token mechanism used to prevent XSRF attacks

HttpClient library recognizes the convention of prefixed JSON responses(which non-executable js code
with ")]}',\n" characters) and automatically strips the string ")]}',\n"
from all responses before further parsing

26. How do you use jquery in Angular?

You can use jquery in Angular using 3 simple steps,
Install the dependency: At first, install the jquery dependency using npm

 npm install --save jquery
Add the jquery script: In Angular-CLI project, add the relative path to jquery in the angular.json file.
"scripts": [
   "node_modules/jquery/dist/jquery.min.js"
]

Start using jquery: Define the element in template. Whereas declare the jquery variable and apply CSS classes on the element.
<div id="elementId">
  <h1>JQuery integration</h1>
</div>
import {Component, OnInit} from '@angular/core';

declare var $: any; // (or) import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    $(document).ready(() => {
      $('#elementId').css({'text-color': 'blue', 'font-size': '150%'});
    });
  }
}

27. What is the reason for No provider for HTTP exception?

This exception is due to missing HttpClientModule in your module. You just need to import in module as below,

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

28. What is router state?

The RouteState is an interface which represents the state of the router as a tree of activated routes.

interface RouterState extends Tree {
  snapshot: RouterStateSnapshot
  toString(): string
}
You can access the current RouterState from anywhere in the Angular app using the Router service and the routerState property.

29. What is slice pipe?

The slice pipe is used to create a new Array or String containing a subset (slice) of the elements. The syntax looks like as below,

{{ value_expression | slice : start [ : end ] }}
For example, you can provide 'hello' list based on a greeting array,
@Component({
  selector: 'list-pipe',
  template: `<ul>
    <li *ngFor="let i of greeting | slice:0:5">{{i}}</li>
  </ul>`
})
export class PipeListComponent {
  greeting: string[] = ['h', 'e', 'l', 'l', 'o', 'm','o', 'r', 'n', 'i', 'n', 'g'];
}

30. What is index property in ngFor directive?

The index property of the NgFor directive is used to return the zero-based index of the item in each iteration. You can capture the index in a template input variable and use it in the template.
For example, you can capture the index in a variable named indexVar and displays it with the todo's name using ngFor directive as below.

<div *ngFor="let todo of todos; let i=index">{{i + 1}} - {{todo.name}}</div>

Click here to check Angular Interview Questions - Part 1

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *