Tech Point Fundamentals

Saturday, November 4, 2023

Angular Interview Questions and Answers - Part 07

Angular Interview Questions and Answers - Part 07

Angular-Interview-Questions-And-Answers

Angular is a popular single-page application design framework and development platform. It is a robust open-source JavaScript framework that is widely used for front-end application development. Nowadays Angular is very common as frontend technology so it is very common for the interview point as well. 

Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 7th part of the Angular Interview Questions and Answer series.

I will highly recommend that please visit the following parts before continuing to this part:



Please do visit our YouTube Channel here to watch Interview Questions and answers and important technology videos.

In this part we will discuss the following Important Angular Interview Questions:

Q072. What are the Lifecycle Hooks of Angular? What is the execution sequence of it?
Q073. How does an Angular application work?
Q074. What is ngOnInit()? How is it defined? 
Q075. What is the difference between a constructor vs. ngOnInit() in Angular? Which one is executed first?
Q076. What is Bootstrapping in Angular? What is a Bootstrapping module? 
Q077. What is the difference between manual vs. automatic bootstrapping in Angular?
Q078. What is a bootstrapped component? Is it necessary for the bootstrapped component to be the entry component?
Q079. What is the use of manual bootstrapping? How do you manually bootstrap an application?
Q080. What is Webpack? What is the use of Webpack in Angular?
Q081. What is Metadata in Angular?
Q082. What are Annotations in Angular?
Q083. What are Decorators in Angular? 

Angular Interview Questions and Answers: Part 07


Q072. What are the Lifecycle Hooks of Angular? What is the execution sequence of it?

In Angular, every component has a lifecycle. Angular creates and renders these components and also destroys them before removing them from the DOM. This is achieved with the help of lifecycle hooks. Lifecycle hooks are predefined methods in Angular that enable developers to access different stages of a component or a directive's lifecycle. This lifecycle begins with the instantiation and rendering of the view and ends with the destruction and removal of the component or directive from the DOM.

When building an Angular app, there are times when we need to execute some code at some specific time or event such as when a component is initialized or displayed on the screen or when the component is being removed from the screen. This is where lifecycle hooks are used for.

To use a lifecycle hook, we can override some methods on a component, such as ngOnInit or ngAfterViewInit. These methods, if available on a component, will be called by Angular automatically. This is why these are called lifecycle hooks.

Angular performs change detection throughout the lifecycle to update the view and component instance whenever necessary. Developers can utilize lifecycle hooks to execute custom code at specific stages, allowing greater control over the functionality and behavior of their components or directives.

anhular-hooks
Source:scaler.com



1. ngOnChanges(): 

The ngOnChanges() hook is called when one or more input properties of the component are changed.  This hook receives a SimpleChanges object containing the previous and current values of the property.

This hook is called before ngOnInit or whenever one or more input properties of the component change. When one or more input properties of a component change, we invoke this method.

2. ngOnInit():

The ngOnInit() is the second lifecycle hook which is the most often used hook.  It is called only once, after the ngOnChanges hook. It is used to initialize the component and set the input properties of the component. 

It initializes the directive or component after Angular first displays the data-bound properties and sets the directive or component's input properties. This method is invoked after component initialization and when input properties have been set. It is an ideal place to perform any initialization logic that depends on the input properties.

3. ngDoCheck(): 

The ngDoCheck() hook is called after ngOnChanges and ngOnInit and is used to detect and act on changes that Angular cannot detect itself. In this hook, we can implement our change detection algorithm.

We call this method during every change detection cycle of the component. It enables you to custom change detection logic.

4. ngAfterContentInit():

The ngAfterContentInit() hook is called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component's view. We invoke this method only after the component's content has been projected into its view.

5. ngAfterContentChecked():

The ngAfterContentChecked() hook is called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.

It responds after Angular checks the content projected into the component. We invoke this method after the component's content has been checked for changes.

6. ngAfterViewInit():

The ngAfterViewInit hook responds after a component's view or a child component's view is initialized. This method is called after we verify that the component's view has been initialized.

7. ngAfterViewChecked(): 

The ngAfterViewChecked() hook is called after ngAfterViewInit. It responds after the component's view or when the child component's view is checked. This method is called after the component's view has been checked for changes.

8. ngOnDestroy():

The ngOnDestroy() hook is called just before Angular destroys the component. This is used to clean up the code and detach event handlers.


Q073. How does an Angular application work?

An Angular application is a single-page application, which means that the entire application lives within a single page, and all of the resources (HTML, CSS, JavaScript, etc.) are loaded when the page is first loaded.

When a user interacts with an Angular application, the Angular framework will automatically update the View to reflect any changes in the data. This means that Angular applications are very responsive and fast, as the user does not need to wait for the page to reload to see the updated data.

Angular applications are also very scalable, as they can be divided into small modules that can be loaded independently of each other. This means that an Angular application can be easily extended with new functionality without having to rewrite the entire application.

Every Angular app consists of a file named angular.json. This file will contain all the configurations of the app. While building the app, the builder looks at this file to find the entry point of the application.  

The working of the Angular application starts with the configuration file angular.json. The builder refers to this file to find the paths, configurations, and the main.ts file. The main.ts file that acts as the entry point for the configuration file. Upon loading the application in a web browser, the following sequence of steps takes place:

Initialization: The Angular framework initiates the application by bootstrapping the root component, which serves as the entry point. The main.ts file creates a browser environment for the application to run, and, along with this, it also calls a function called bootstrapModule, i.e. AppModule which bootstraps the application.

Component Rendering: Angular renders components based on their predefined templates. Each component contains a template that describes the structure and layout of the user interface (UI).

Angular calls the index.html file. This file consequently calls the root component that is app-root. The root component is defined in app.component.ts. The HTML template of the root component is displayed inside the <app-root> tags.

Data Binding: Angular uses multiple data binding, which facilitates the synchronization of data between the component’s model and the view. This synchronization allows for dynamic updates in real-time, ensuring that the view consistently and accurately represents the current state of the data.

Component Interaction: Angular allows components to communicate with each another through @input and @output properties, as well as services, facilitating the exchange of data and functionality across different parts of the application.

Event Handling: Angular manages user interactions, such as button clicks or form submissions, by capturing and responding to events. These events trigger specific actions or updates within the application.

Dependency Injection: Angular has dependency injection to handle the application’s dependencies and promote modularity. This simplifies the integration of services and reusable code modules that provide specific functionality to components.

Routing: Angular incorporates a router module that enables navigation within the application. Routes are defined to determine which components are displayed based on the current URL or user actions.

Compilation and Bundling: Before prod deployment, an Angular application is compiled and bundled. This process optimizes performance by reducing file sizes and merging multiple files into a single bundle.

Deployment: Finally the application can be deployed to a web server or hosting service, making it accessible to users. 

Q074. What is ngOnInit()? How is it defined? 

The ngOnInit is the most often used lifecycle hook and a callback method that is run by Angular to indicate that a component has been created. It is called after the constructor is called or after the component’s inputs have been initialized. It accepts no arguments and returns a void type.

It is used to perform any additional initialization that is required for the component. The ngOnInit is commonly used to call services or to set up subscriptions.

If one has to process a lot of data during component creation, it’s better to do it inside the ngOnInit hook rather than the constructor.

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor() {   }
    ngOnInit() {
      this.processData();
    }
    processData(){
      // Write your logic...
    }
  title = 'tech-point-app';
}

Q075. What is the difference between a constructor vs. ngOnInit() in Angular? Which one is executed first?

In Angular, both constructor and ngOnInit are commonly used in components. While they may seem similar at first, they serve different purposes and have some key differences.

Constructor: A Constructor is a special method that is automatically called when an instance of a class is created. It initializes the properties of the class and does any other necessary setup. In Angular, constructors are used to inject dependencies, such as services or other components, into a component.

ngOnInit: ngOnInit is a lifecycle hook in Angular that is called after the constructor is called or after the component’s inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions.

ConstructorVsOnInit
Source: v2.angular.io

Constructor vs. ngOnInit: 

Following are the key differences between Constructor and ngOnInit:


ConstructorVsNgOnInit


Q076. What is Bootstrapping in Angular? What is a Bootstrapping module? 

Bootstrapping is the process of initializing or loading the Angular application upon startup. In Angular, the root module is used for bootstrapping or launching the application which is known as the "Bootstrapping Module". A Bootstrapping Module is present in every Angular app and usually, it is stored in the AppModule class. In fact, the Bootstrapping module is also called the AppModule.

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

A bootstrapping module is the main entry point of an Angular application. Every application contains at least one Angular module, which is referred to as the bootstrapping module. It is responsible for starting the application and initializing the root component. 

The bootstrapping module is typically defined in the main.ts file and is configured in the angular AppModule. It sets up the necessary environment, loads required modules, and invokes the Angular platform to start the application. The bootstrapping module plays a crucial role in the Angular application's lifecycle.

platformBrowserDynamic().bootstrapModule(AppModule);

Angular takes the following steps to load our first view.

  1. Loading Index.html
  2. Loading Angular & other third-party libraries
  3. Executing application entry point i.e. main.ts file
  4. Load & execute Root Module i.e. app.module.ts
  5. Executing the Root Component i.e. app.component.ts
  6. Displays the template i.e. app.component.html

When index.html is loaded, the Angular core libraries and third-party libraries are loaded. Now the angular needs to locate the entry point. The entry point of our application is main.ts. The Angular finds the entry point from the configuration file angular.json. This file is located in the root folder of the project. 

Q077. What is the difference between manual vs. automatic bootstrapping in Angular?

Angular supports both manual and automatic bootstrapping.

Manual Bootstrapping: 

Manual Bootstrapping gives more control to developers about how and when they need to initialize the Angular app. It is very useful in places where developers wish to perform other tasks and operations before Angular compiles the page. 

You can use the ngDoBootstrap() hook for a manual bootstrapping of the application instead of using a bootstrap array in @NgModule annotation.

Default or Automatic Bootstrapping: 

Automatic bootstrapping can be used to add the ng-app directive to the application’s root, often on the tag if developers need Angular to automatically bootstrap the application. Angular loads the associated module once it finds the ng-app directive and, further, compiles the DOM.

Q078. What is a bootstrapped component? Is it necessary for the bootstrapped component to be the entry component?

A bootstrapped component is the entry point component that Angular loads into the DOM during the bootstrap process or application launch time.

Yes, the bootstrapped component needs to be an entry component. This is because the bootstrapping is an imperative process. Generally, this bootstrapped or root component is named AppComponent in your root module using the bootstrap property.

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

Q079. What is the use of manual bootstrapping? How do you manually bootstrap an application?

Manual Bootstrapping gives more control to developers regarding how and when they need to initialize the Angular app. It is very useful in places where developers wish to perform other tasks and operations before Angular compiles the page. 

Suppose we have two components A component and B component. We have to decide during runtime which one should be used in the application. In this case, we can not use automatic bootstrapping.

You can use the ngDoBootstrap() hook for a manual bootstrapping of the application instead of using a bootstrap array in @NgModule annotation. This hook is part of the DoBootstap interface. It also works in AOT as well.

interface DoBootstrap {
  ngDoBootstrap(appRef: ApplicationRef): void
}

The module needs to implement the above interface to use the hook for bootstrapping.

class AppModule implements DoBootstrap {
  ngDoBootstrap(appRef: ApplicationRef) {
  appRef.bootstrap(AppComponent);
  }
}

Q080. What is Webpack? What is the use of Webpack in Angular?

WebPack is an open-source JavaScript frameworkWebpack is a powerful module bundler, which scans your web application looking for javascript and css files and merges them into one ( or more) big files.  

Webpack can bundle any kind of file like JavaScript, CSS, SASS, LESS, images, HTML, & fonts, etc. Webpack also comes with a Development Server that supports hot module reloading.

The Angular CLI uses Webpack as a module bundler. Webpack needs a lot of configuration options to work correctly. The Angular CLI sets up all these configuration options behind the scenes.

Q081. What is Metadata in Angular?

Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators. Decorators are the core concept when developing with Angular. 

Using metadata is how we tell Angular how to process a class. When we use a component, it acts as a class unless we tell that it’s a component, and we do this with the help of metadata. Metadata is attached in TypeScript using a decorator. Decorators are functions that know the configuration of classes and how they are supposed to work.

There are different types of metadata or decorators in Angular like class decorators, property decorators, method decorators, and parameter decorators.

@Component({
  selector:    'app-hero-list',
  templateUrl: './hero-list.component.html',
  providers:  [ HeroService ]
})

Here the @Component decorator identifies the class immediately below it as a component class and specifies its metadata. The @Component metadata for a class component tells Angular where to get the major building blocks that it needs to create and present the component and its view.

Q082. What are Annotations in Angular?

The angular team announced AtScript as their language extension to JavaScript. AtScript comes with features like Type AnnotationsField Annotations, and MetaData Annotations.

In Angular, an annotation refers to a type of metadata that is used to enhance and provide additional information about a class or its members. Annotations are decorators at the class level.  Annotations are commonly used in Angular to configure and decorate various parts of an application, including components, services, and modules.

Annotations are language-specific features that are hard-coded. When a user annotates a class, the compiler adds an annotations property to the class, saves an annotation array in it, and then attempts to instantiate an object with the same name as the annotation, providing the metadata into the constructor.

So annotations in Angular are used for creating an annotation array. They are the metadata set on the class that is used to reflect the Metadata library. Annotations are ways of adding metadata to a class or its members using decorators. The decorators are a TypeScript feature.

To add annotations to classes, methods, and properties, we use the @ symbol followed by the decorator name:

import { Injectable } from '@angular/core';
@Injectable()export class MySeat { ...}

Annotations are specifically used to supply information to the Angular compiler on how to process a class and/or its members. We may use them to specify various things, such as the class's dependencies, how it should be injected, and how it can be used in templates.

@Component({
  selector: 'tabs',
  template: `<ul><li>Tab A</li><li>Tab B</li></ul>`
})
export class Tabs {
}

Here @Component annotation adds some metadata to the class to give it a specific meaning. If you remove this annotation, what would be left is just an empty class that doesn’t have any special meaning. They are a declarative way to add metadata to code. Annotations are decorators at the class level. 

Annotations are not available in browsers of today so we need to transpile it to something that can run in current browsers. We have a couple of transpilers we can choose from like Babel compiler, Google's Traceur compiler, and TypeScript's TSC compiler. If you translate the above code using Traceur:

var Tabs = (function () {
  function Tabs() {}
  Tabs.annotations = [
  new ComponentMetadata({...}),
  ];
  return Tabs;
})

So in the end, a class is just a function, which is also just an object, and all annotations end up as instance calls on the annotations property of the class. 

Angular expects the metadata on annotations and parameter properties of classes. If Traceur did not translate them to those particular properties, Angular wouldn’t know where to get the metadata.

Q083. What are Decorators in Angular? 

Decorators are a proposed standard for ECMAScript 2016 by Yehuda Katz, to annotate and modify classes and properties at design time. This sounds pretty much like what annotations do. It looks exactly like an AtScript annotation, but it is not. Also with decorators, we can build our custom annotations as well.

In Angular decorators are functions that are invoked with a prefixed @ symbol, and are immediately followed by a class, method, or property. They allow a service, directive, or filter to be changed before use. Basically, a decorator provides configuration metadata that determines how the component, class, or function should be processed, instantiated, and used at runtime. Decorators are implemented by the TypeScript compiler

@decoratorExpression
class MyClass { }

A decorator is just a function that gives you access to the target that needs to be decorated. If you see the corresponding decorator implementation for @decoratorExpression above, it could look like this:

function decoratorExpression(target) {    
  target.annotated = true;
}

Decorators are a fundamental concept in TypeScript. Decorators are design patterns or functions that define how Angular features work. Angular defines several decorators that attach specific kinds of metadata to classes so that the system knows what those classes mean and how they should work. 

TypeScript supports decorators but doesn’t know about Angular-specific annotations. So what the framework behind the scenes does is, it comes with metadata annotation implementations, which are then passed to the decorator generator to make decorators out of them. 

import { ComponentMetadata as Component } from '@angular/core';

Here you can see that we are actually importing the metadata rather than the decorator. This is simply just because Traceur doesn’t understand decorators, but does understand @Component annotations.

For example @Component and @NgModel decorator:

@Component({  
  selector: 'example-component',  
  template: '<div>This is a component!</div>',  
})  

@NgModule({  
  imports: [],  
  declarations: [],  
})  

Similarly, we can have other decorators as well like class, property, methods, and parameter decorators.



Recommended Articles



Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.