FrontendDeveloper.in

Angular Interview Questions

  • Question 166

    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,

    and define the htmlSnippet property from any component

    export class myComponent {
    htmlSnippet: string = '**Hello World**, Angular';
    }
    

    Unfortunately this property could cause Cross Site Scripting (XSS) security bugs when improperly handled.

  • Question 167

    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,

    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.

  • Question 168

    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,

    1. Inject DomSanitizer: You can inject DomSanitizer in component as parameter in constructor

    2. Mark the trusted value by calling some of the below methods

    3. bypassSecurityTrustHtml

    4. bypassSecurityTrustScript

    5. bypassSecurityTrustStyle

    6. bypassSecurityTrustUrl

    7. 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);
    
  • Question 169

    Is it safe to use direct DOM API methods in terms of security?

    No,the built-in browser DOM APIs or methods don't automatically protect you from security vulnerabilities. In this case it is recommended to use Angular templates instead of directly interacting with DOM. If it is unavoidable then use the built-in Angular sanitization functions.

  • Question 170

    What is DOM sanitizer?

    DomSanitizer is used to help preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts.

  • Question 171

    How do you support server side XSS protection in Angular application?

    The server-side XSS protection is supported in an angular application by using a templating language that automatically escapes values to prevent XSS vulnerabilities on the server. But don't use a templating language to generate Angular templates on the server side which creates a high risk of introducing template-injection vulnerabilities.

  • Question 172

    Does Angular prevent 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.

    1. HttpClient supports a token mechanism used to prevent XSRF attacks
    2. 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
  • Question 173

    What are Http Interceptors?

    Http Interceptors are part of @angular/common/http, which inspect and transform HTTP requests from your application to the server and vice-versa on HTTP responses. These interceptors can perform a variety of implicit tasks, from authentication to logging.

    The syntax of HttpInterceptor interface looks like as below,

    interface HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
    }
    

    You can use interceptors by declaring a service class that implements the intercept() method of the HttpInterceptor interface.

    @Injectable()
    export class MyInterceptor implements HttpInterceptor {
    constructor() {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    ...
    }
    }
    

    After that you can use it in your module,

    @NgModule({
    ...
    providers: [
    {
    provide: HTTP_INTERCEPTORS,
    useClass: MyInterceptor,
    multi: true
    }
    ]
    ...
    })
    export class AppModule {}
    
  • Question 175

    Are multiple interceptors supported in Angular?

    Yes, Angular supports multiple interceptors at a time. You could define multiple interceptors in providers property:

    providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyFirstInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: MySecondInterceptor, multi: true }
    ],
    

    The interceptors will be called in the order in which they were provided. i.e, MyFirstInterceptor will be called first in the above interceptors configuration.

  • Question 176

    How can I use interceptor for an entire application?

    You can use same instance of HttpInterceptors for the entire app by importing the HttpClientModule only in your AppModule, and add the interceptors to the root application injector. For example, let's define a class that is injectable in root application.

    @Injectable()
    export class MyInterceptor implements HttpInterceptor {
    intercept(
    req: HttpRequest<any>,
    next: HttpHandler
    ): Observable<HttpEvent<any>> {
    
    return next.handle(req).do(event => {
    if (event instanceof HttpResponse) {
    // Code goes here
    }
    });
    
    }
    }
    

    After that import HttpClientModule in AppModule

    @NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, HttpClientModule],
    providers: [
    { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
    ],
    bootstrap: [AppComponent]
    })
    export class AppModule {}
    
  • Question 177

    How does Angular simplify Internationalization?

    Angular simplifies the below areas of internationalization,

    1. Displaying dates, number, percentages, and currencies in a local format.
    2. Preparing text in component templates for translation.
    3. Handling plural forms of words.
    4. Handling alternative text.
  • Question 178

    How do you manually register locale data?

    By default, Angular only contains locale data for en-US which is English as spoken in the United States of America . But if you want to set to another locale, you must import locale data for that new locale. After that you can register using registerLocaleData method and the syntax of this method looks like below,

    registerLocaleData(data: any, localeId?: any, extraData?: any): void
    

    For example, let us import German locale and register it in the application

    import { registerLocaleData } from '@angular/common';
    import localeDe from '@angular/common/locales/de';
    
    registerLocaleData(localeDe, 'de');
    
  • Question 179

    What are the four phases of template translation?

    The i18n template translation process has four phases:

    1. Mark static text messages in your component templates for translation: You can place i18n on every element tag whose fixed text is to be translated. For example, you need i18n attribute for heading as below,
    <h1 i18n>Hello i18n!</h1>
    
    1. Create a translation file: Use the Angular CLI xi18n command to extract the marked text into an industry-standard translation source file. i.e, Open terminal window at the root of the app project and run the CLI command xi18n.
    ng xi18n
    

    The above command creates a file named messages.xlf in your project's root directory.

    Note: You can supply command options to change the format, the name, the location, and the source locale of the extracted file.

    1. Edit the generated translation file: Translate the extracted text into the target language. In this step, create a localization folder (such as locale)under root directory(src) and then create target language translation file by copying and renaming the default messages.xlf file. You need to copy source text node and provide the translation under target tag. For example, create the translation file(messages.de.xlf) for German language
    <trans-unit id="greetingHeader" datatype="html">
    <source>Hello i18n!</source>
    <target>Hallo i18n !</target>
    <note priority="1" from="description">A welcome header for this sample</note>
    <note priority="1" from="meaning">welcome message</note>
    </trans-unit>
    
    1. Merge the completed translation file into the app: You need to use Angular CLI build command to compile the app, choosing a locale-specific configuration, or specifying the following command options.

    2. --i18nFile=path to the translation file

    3. --i18nFormat=format of the translation file

    4. --i18nLocale= locale id

  • Question 180

    What is the purpose of i18n attribute?

    The Angular i18n attribute marks translatable content. It is a custom attribute, recognized by Angular tools and compilers. The compiler removes it after translation.

    Note: Remember that i18n is not an Angular directive.

Get LinkedIn Premium at Rs 399