Skip to main content

Angular interview questions part 1

 1)Explain component life cycle?





Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The representation of lifecycle in pictorial representation as follows,

The description of each lifecycle method is as below,


ngOnChanges: When the value of a data bound property changes, then this method is called. If no property then no call.

ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.

ngDoCheck: This is for the detection and to act on changes that Angular can't or won't detect on its own.

Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run.


ngAfterContentInit: This is called in response after Angular projects external content into the component's view.

Called once after the first ngDoCheck().


ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.

Called after ngAfterContentInit() and every subsequent ngDoCheck().



ngAfterViewInit: This is called in response after Angular initializes the component's views and child views.

ngAfterViewChecked: This is called in response after Angular checks the component's views and child views.

ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.


2)What is decorators in angular?

A class decorator is a decorator that appears immediately before a class definition, which declares the class to be of the given type, and provides metadata suitable to the type

Decorator is a special kind of declaration that can be attached to a class declarationmethodaccessorproperty, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.


The following list of decorators comes under class decorators,


@Component()

@Directive()

@Pipe()

@Injectable()

@NgModule()

3)What is module in Angular?

Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Lets take an example of app.module.ts root module declared with @NgModule decorator as below,

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

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

The NgModule decorator has five important(among all) options

  1. The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
  2. The declarations option is used to define components in the respective module
  3. The bootstrap option tells Angular which Component to bootstrap in the application
  4. The providers option is used to configure set of injectable objects that are available in the injector of this module.
  5. The entryComponents option is a set of components dynamically loaded into the view.


4)What are selectores in Angular?

If we say in simple term selector is name which is used in our view like html tag. as we all know angular2 is component based. so selector is just provide the name of the component which is being called by its className in the directives list and called by selector name in the view of the another component like this:-


Selectors are like CSS selectors. They can be attribute selectors, tag selectors, class selectors, id selectors and combinations of these. 

5)What happens in aot?

Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time. For AOT compilation, include the --aot option with the ng build or ng serve command as below,

ng build --aot
ng serve --aot
Note: The ng build command with the --prod meta-flag (ng build --prod) compiles with AOT by default.

Below are the list of AOT benefits,

  1. Faster rendering: The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app.
  2. Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests.
  3. Smaller Angular framework download size: Browser doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload.
  4. Detect template errors earlier: Detects and reports template binding errors during the build step itself
  5. Better security: It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.

6)What is the difference between ng build and ng serve?


The ng serve command is intentionally for fast, local and iterative developments and also for builds, watches and serves the application from a local CLI development server.


Also, if you running the angular app using ng serve and if you make any changes to your app, the changes are captured and reflected instantaneously on the UI. This avoids starting and stopping the server again and again.

The ng build command is intentionally for building the apps and deploying the build artifacts.


Both commands ng build and ng serve will clear the output folder before they build the project.

The main difference is – The ng build command writes generated build artifacts to the output folder and the ng serve command does not. By default, the output folder is - dist/.


Also the ng serve builds artifacts from memory instead for a faster development experience.
The ng build command generates output files just once and does not serve them.


The ng build --watch command will regenerate output files when source files change. This --watch flag is useful if you're building during development and are automatically re-deploying changes to another server.



7)What if we don't want to load index.html and change file name?

The index option supports a longhand form as follows:


In Angular.json file we can change it in  artifacts options index also for particular env we can set it.

"index": {
  "input": "src/index.html", // used index file from your project folder
  "output": "index.html", // created index file in your outputPath
},

angular.json example:

"architect": {
  "build": {
    "options": {
      "outputPath": "dist/myproject",
      "index": "src/index.html", // default index file (shorthand form)
    },
    "configurations": {
      "production": {
        "index": { // production index replacement (longhand form)
          // use the file at 'src/index.prod.html' in production builds
          "input": "src/index.prod.html",
          // create the index file under 'index.html' in your outputPath
          "output": "index.html"
        }
      }
    }
  }
}

This feature was added in Angular Cli v8.2.0-next.0.




8)What is pipe? How to create it



  1. A pipe takes in data as input and transforms it to a desired output. For example, let us take a pipe to transform a component's birthday property into a human-friendly date using date pipe.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-birthday',
      template: `<p>Birthday is {{ birthday | date }}</p>`
    })
    export class BirthdayComponent {
      birthday = new Date(1987, 6, 18); // June 18, 1987
    }

Create custom pipe?



Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,

  1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,
        @Pipe({name: 'myCustomPipe'})
  2. The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipeTransform would be as below,
    interface PipeTransform {
      transform(value: any, ...args: any[]): any
    }
  3. The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier.
    template: `{{someInputValue | myCustomPipe: someOtherValue}}`

  1. You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,
      import { Pipe, PipeTransform } from '@angular/core';
    
      @Pipe({name: 'customFileSizePipe'})
      export class FileSizePipe implements PipeTransform {
        transform(size: number, extension: string = 'MB'): string {
          return (size / (1024 * 1024)).toFixed(2) + extension;
        }
      }
    Now you can use the above pipe in template expression as below,
       template: `
          <h2>Find the size of a file</h2>
          <p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
        `

 Back to Top

  1. What is the difference between pure and impure pipe?

    A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.


  1. What are observables?

    Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
  2. Does the order of paths matter?

    The other paths are completely different, so no, order does not matter for these. The routing engine won't confuse followers and followers/:username/:userid - as the Angular guide points out, :username and :userid are required parameters, so need to be present, as in followers/testuser/10.

    It does matter when two routes conflict tho, as in posts and **. The path /posts will be matched by both routes, and the first one wins.

    This is why the wildcard is at the end. As a basic rule, always try to order by most specific to least specific.

Comments

Popular posts from this blog

Node.js: Extract text from image using Tesseract.

In this article, we will see how to extract text from images using Tesseract . So let's start with this use-case, Suppose you have 300 screenshot images in your mobile which has an email attribute that you need for some reason like growing your network or for email marketing. To get an email from all these images manually into CSV or excel will take a lot of time. So now we will check how to automate this thing. First, you need to install Tesseract OCR( An optical character recognition engine ) pre-built binary package for a particular OS. I have tested it for Windows 10. For Windows 10, you can install  it from here. For other OS you make check  this link. So once you install Tesseract from windows setup, you also need to set path variable probably, 'C:\Program Files\Tesseract-OCR' to access it from any location. Then you need to install textract library from npm. To read the path of these 300 images we can select all images and can rename it to som...

Globant part 1

 1)call,apply,bind example? Ans: a. call Method: The call method is used to call a function with a given this value and arguments provided individually. Javascript code: function greet(name) {   console.log(`Hello, ${name}! I am ${this.role}.`); } const person = {   role: 'developer' }; greet.call(person, 'Alice'); // Output: Hello, Alice! I am developer. In this example, call invokes the greet function with person as the this value and passes 'Alice' as an argument. b. apply Method: The apply method is similar to call, but it accepts arguments as an array. Javascript code: function introduce(language1, language2) {   console.log(`I can code in ${language1} and ${language2}. I am ${this.name}.`); } const coder = {   name: 'Bob' }; introduce.apply(coder, ['JavaScript', 'Python']); // Output: I can code in JavaScript and Python. I am Bob. Here, apply is used to invoke introduce with coder as this and an array ['JavaScript', 'Pyt...

Maximizing MongoDB Performance: A Guide to Effective Indexing Strategies

Introduction: MongoDB, a leading NoSQL database, offers unparalleled flexibility and scalability. However, achieving optimal query performance in MongoDB often relies on implementing effective indexing strategies. In this article, we'll delve into various indexing techniques and provide real-world examples to demonstrate their impact on query performance. Single Field Index: Single field indexes are ideal for accelerating queries that filter, sort, or search based on a specific field. Let's consider a scenario where we have a collection of user profiles, and we frequently query users by their username field: db.users.createIndex({ "username": 1 }) This index significantly speeds up queries like: db.users.find({ "username": "john_doe" }) Compound Index: Compound indexes are invaluable when queries involve multiple fields. Suppose we have a collection of products and often filter by both category and price: db.products.createIndex({ "category...