Top 90+ Angular Interview Questions And Answers

The main difference between `ng add` and `npm install` lies in their purpose and functionality within the Angular ecosystem. 1. `ng add`: This is a command specific to the Angular CLI (Command Line Interface). It is used to add new packages, libraries, or schematics to an Angular project. When you run `ng add`, it performs several tasks automatically, such as installing the necessary packages, configuring the project, and making any required changes to the project's files. The `ng add` command is often used to quickly integrate third-party libraries or extensions into an Angular project with minimal effort. Suppose you want to add the Angular Material library to your Angular project. Instead of manually configuring and installing Angular Material, you can use the `ng add` command to simplify the process. Here's how you would do it:

   ng add @angular/material

When you run this command, the Angular CLI will perform the following tasks: - Install the `@angular/material` package and its dependencies using `npm install`. - Configure the project to use Angular Material by updating the `angular.json` file. - Import and configure the necessary modules and styles in the project's files (e.g., `app.module.ts` and `styles.scss`). `ng add` is a convenient way to add Angular-specific packages or schematics to your project while automating the necessary setup steps. 2. `npm install`: This is a general command provided by npm (Node Package Manager) for installing packages from the npm registry. It is not specific to Angular but is used across various JavaScript and Node.js projects. When you run `npm install `, it installs the specified package and its dependencies into the project. It typically updates the `package.json` file to include the installed package as a dependency. However, `npm install` does not perform any specific configuration or modification of the project's files. Let's say you want to install the `lodash` library, which is a popular utility library for JavaScript. In this case, you would use the `npm install` command directly, as follows:

   npm install lodash

Running this command will: - Fetch the `lodash` package and its dependencies from the npm registry. - Install the package locally within your project's `node_modules` directory. - Update the `package.json` file to include `lodash` as a dependency. `npm install` is a general-purpose command used to install any package from the npm registry into your project, regardless of the specific framework or library being used. In summary, `ng add` is a specialized command within the Angular CLI that automates the installation and configuration of packages specifically designed for Angular projects. On the other hand, `npm install` is a general command provided by npm to install packages from the npm registry into any JavaScript or Node.js project, including Angular projects.
Custom directives are a feature in Angular that allow developers to extend the functionality of HTML by creating their own custom HTML elements or attributes. With custom directives, developers can define their own behavior, such as adding event listeners, modifying the DOM, or manipulating data. To create a custom directive in Angular, follow these steps: 1) Create a new directive using the @Directive decorator. The decorator specifies the selector for the directive and any inputs, outputs, and other options. 2) Define the directive class, which contains the logic for the directive. The class should implement the OnInit and OnDestroy interfaces to handle the initialization and destruction of the directive. 3) Add the directive to the declarations array in the module that will use it. This tells Angular that the directive should be available for use in that module. Here is an example of a simple custom directive that changes the background color of an element:

import { Directive, ElementRef, Renderer2 } from '@angular/core';

  selector: '[appHighlight]'
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) { }

  ngOnInit() {
    this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');

  ngOnDestroy() {
    this.renderer.removeStyle(this.el.nativeElement, 'background-color');

In this example, the HighlightDirective sets the background color of an element to yellow when it is initialized, and removes the background color when it is destroyed. The ElementRef and Renderer2 classes are used to access and manipulate the element in the DOM. To use this directive in a template, simply add the appHighlight attribute to an element:

  <p apphighlight>
  This text will have a new yellow background.

When the template is rendered, the HighlightDirective will be applied to the element, changing its background color to yellow.
The canActivateChild route guard in Angular allows you to check if a user is allowed to activate child routes. It is used to protect child routes of a particular route from being activated if certain conditions are not met. When a user navigates to a child route, Angular checks if there is an associated canActivateChild guard in the parent route's route configuration. If there is, Angular executes the guard before activating the child route. The canActivateChild guard is implemented as a service that implements the CanActivateChild interface. This interface has a single method, canActivateChild(), which returns a boolean or a promise that resolves to a boolean. If the method returns true, the child route is activated. If it returns false or a promise that resolves to false, the child route is not activated, and the user is redirected to a different route, or a custom error page is displayed. Here is an example of how to use the canActivateChild route guard:

import { Injectable } from '@angular/core';
import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';

  providedIn: 'root'
export class AuthGuard implements CanActivateChild {

    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable | Promise | boolean {
    // Check if the user is authenticated
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      // If the user is not authenticated, redirect to the login page
      return false;

In this example, we have an AuthGuard service that implements the CanActivateChild interface. The canActivateChild() method checks if the user is authenticated using a method isAuthenticated() provided by an AuthService. If the user is authenticated, the method returns true, allowing the child route to be activated. If the user is not authenticated, the method navigates to the login page and returns false, preventing the child route from being activated. To use the AuthGuard service, you can add it to the canActivateChild property in the route configuration for the parent route that guards its child routes:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

const routes: Routes = [
    path: 'parent',
    component: ParentComponent,
    canActivateChild: [AuthGuard],
    children: [
        path: 'child',
        component: ChildComponent

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }

In this example, the canActivateChild property is set to an array containing the AuthGuard service. This guards the child route with the AuthGuard. Still confused? if yes, check link canActivateChild - tektutorialshub for explanation
`ng serve` and `npm start` are both commands used in web development, but they serve different purposes depending on the context. Let's look at the differences between `ng serve` and `npm start` with some examples: 1. `ng serve` Example: Let's say you're working on an Angular project and want to run it locally for development purposes. You would navigate to your project directory in the command line and run the following command:

   ng serve

This command would compile your Angular application, bundle the assets, start a development server, and watch for changes. It will then provide you with a local URL (usually http://localhost:4200) where you can access and test your application in the browser. The development server will also automatically reload the application whenever you make changes to the code. 2. `npm start` Example: Suppose you're working on a Node.js project that has a `start` script defined in the `package.json` file. The `start` script is set to execute the main application file, `index.js`. To start your application, you would navigate to the project directory and run the following command:

   npm start

This command will execute the command specified in the `start` script of the `package.json` file, which in this case is running `index.js`. It could be any command you specify. For example, you might use `npm start` to launch a web server, initiate a build process, or perform any other necessary actions to start your application in a production or deployment environment. In summary, `ng serve` is used specifically for running an Angular project locally during development, providing a development server and automatic reloading. On the other hand, `npm start` is a more generic command used in Node.js projects to execute a command specified in the `start` script, often used for starting an application in a production environment.
The `dependencies` and `devDependencies` properties in the `package.json` file are used to manage different types of dependencies in a Node.js project. Here's the difference between them: 1. `dependencies`: - The `dependencies` property is used to list the packages that are required for the project to run in a production or deployment environment. - These packages are necessary for the application's core functionality and are typically required at runtime. - When you install the project dependencies using `npm install`, the packages listed in the `dependencies` section are installed. Example:

   "dependencies": {
     "express": "^4.17.1",
     "lodash": "^4.17.21"

2. `devDependencies`: - The `devDependencies` property is used to list the packages that are only required during development, such as testing frameworks, build tools, and development-specific utilities. - These packages are not necessary for the application to run in a production environment but are helpful during development and testing phases. - When you install the project dependencies along with dev dependencies using `npm install`, the packages listed in both the `dependencies` and `devDependencies` sections are installed. Example:
   "devDependencies": {
     "mocha": "^9.0.3",
     "nodemon": "^2.0.13"

By separating dependencies into `dependencies` and `devDependencies`, you can distinguish between packages required for production and those required for development. This separation helps reduce the size of the production deployment by excluding unnecessary development-related packages. Conclusion To summarize, `dependencies` includes packages needed for the application to run in a production environment, while `devDependencies` includes packages required during development and testing but are not necessary for the production deployment.
In Angular, a ReplaySubject is a type of subject provided by the RxJS library. It is a variant of the Subject class and allows you to multicast values to multiple subscribers. A ReplaySubject remembers and replays a specific number of values to any subscriber that subscribes to it. When a new subscriber subscribes to a ReplaySubject, it will immediately receive the buffered values, up to a specified buffer size or timeframe. The key features of a ReplaySubject are: 1. Buffering: A ReplaySubject keeps a buffer of values that it has emitted. You can specify the maximum number of values to buffer using the buffer size parameter when creating the ReplaySubject. 2. Subscription: When a new subscriber subscribes to a ReplaySubject, it immediately receives the buffered values. If the buffer size is reached, older values are dropped from the buffer to accommodate new values. 3. Timeframe: In addition to the buffer size, you can also specify a timeframe for the ReplaySubject. With a timeframe, the ReplaySubject will only buffer values emitted within a specific time window. ReplaySubjects are useful in scenarios where you want subscribers to receive previously emitted values, even if they subscribe at a later time. For example, if you have a component that needs to fetch some initial data on initialization, you can use a ReplaySubject to cache the data and ensure that any subsequent subscribers receive the cached values. Here's an example usage of a ReplaySubject in Angular:

import { ReplaySubject } from 'rxjs';

// Create a ReplaySubject with a buffer size of 3
const subject = new ReplaySubject(3);

// Emit values to the ReplaySubject'Value 1');'Value 2');'Value 3');

// Subscribe to the ReplaySubject
subject.subscribe(value => console.log('Received:', value));

// Output: Received: Value 1, Received: Value 2, Received: Value 3

// Emit another value'Value 4');

// Output: Received: Value 4 (new subscriber receives the latest value)

// Subscribe again after some time
setTimeout(() => {
  subject.subscribe(value => console.log('Received later:', value));
}, 2000);

// Output: Received later: Value 2, Received later: Value 3, Received later: Value 4

In the example above, the ReplaySubject buffers the last 3 emitted values. When a new subscriber subscribes, it immediately receives the buffered values. The second subscriber, which subscribes after some time, receives the buffered values that were emitted within the specified timeframe. ReplaySubjects are a powerful tool in Angular when you need to share and replay values among multiple subscribers, especially when dealing with asynchronous data streams.
In Angular, there is a distinction between adding styles and scripts in the `angular.json` configuration file and adding them directly in the `index.html` file. Here's a breakdown of the key differences: 1. `angular.json`: The `angular.json` file is the configuration file for an Angular project. It contains various settings and options related to the project's build process, including the configuration for styles and scripts. In the `angular.json` file, you can specify the styles and scripts that should be included as part of the project build process. The styles are typically specified using the `"styles"` property, which accepts an array of file paths for CSS or Sass files. The scripts are typically specified using the `"scripts"` property, which accepts an array of file paths for JavaScript or TypeScript files. These styles and scripts defined in the `angular.json` file will be automatically included and bundled as part of the build process. They will be loaded and applied to the application during runtime. 2. `index.html`: The `index.html` file is the main HTML file for an Angular application. It is the entry point for the application and contains the basic structure of the HTML document. In the `index.html` file, you can add external stylesheets or scripts directly using `<link>` and `<script>` tags. These tags reference external CSS or JavaScript files hosted on a server or included from a CDN. By including them in the `index.html` file, they will be loaded by the browser when the application is accessed. The styles and scripts added directly in the `index.html` file are separate from the ones specified in the `angular.json` file. They are not part of the build process or bundling performed by Angular. Instead, they are loaded and applied by the browser directly when the `index.html` file is loaded. In summary, the key differences are: - Styles and scripts specified in the `angular.json` file are part of the Angular build process and bundled with the application during build time. - Styles and scripts added directly in the `index.html` file are loaded by the browser at runtime, separate from the Angular build process. Typically, it is recommended to use the `angular.json` file for including styles and scripts that are part of the project and managed by Angular. On the other hand, adding external stylesheets or scripts in the `index.html` file is useful for including third-party libraries or custom styles and scripts that are not managed by Angular.
In RxJS, a popular library for reactive programming, observables can be categorized into two types: cold observables and hot observables. The key difference between these two types lies in how they handle the emission and subscription of values. 1. Cold Observables: A cold observable starts emitting values when a subscription is made. Each subscription to a cold observable triggers a separate execution of the observable's logic. In other words, the data stream is independent for each subscriber, and each subscriber receives the full sequence of emitted values from the beginning. For example:

import { Observable } from 'rxjs';

const coldObservable = new Observable(observer => {
  console.log('Observable logic');;;;

coldObservable.subscribe(value => console.log('Subscriber 1:', value));
coldObservable.subscribe(value => console.log('Subscriber 2:', value));


Observable logic
Subscriber 1: 1
Subscriber 1: 2
Subscriber 1: 3
Observable logic
Subscriber 2: 1
Subscriber 2: 2
Subscriber 2: 3

In the example above, each subscriber triggers the execution of the observable logic separately, and both subscribers receive the complete sequence of emitted values. 2. Hot Observables: A hot observable, on the other hand, emits values regardless of subscriptions. It starts emitting values immediately upon creation, and subscribers receive only values emitted after they subscribe. The data stream is shared among subscribers, and late subscribers may miss previously emitted values. For example:

import { Subject } from 'rxjs';

const hotObservable = new Subject<number>();;;;

hotObservable.subscribe(value => console.log('Subscriber 1:', value));;;

hotObservable.subscribe(value => console.log('Subscriber 2:', value));;;

Subscriber 1: 4
Subscriber 1: 5
Subscriber 1: 6
Subscriber 1: 7
Subscriber 2: 6
Subscriber 2: 7

In the example above, the hot observable starts emitting values immediately. Subscriber 1 subscribes after the first three values have been emitted and receives subsequent values. Subscriber 2 subscribes later and only receives values emitted after its subscription. Hot observables are commonly used for events or continuous data streams, where the values are being produced independently of subscriptions. In summary, the main difference between cold observables and hot observables is that cold observables start emitting values upon subscription and each subscription triggers a separate execution, while hot observables emit values regardless of subscriptions and late subscribers may miss previously emitted values.

The set of injectable objects that are available in the injector of this module.


The set of components, directives, and pipes (declarables) that belong to this module.


The set of NgModules whose exported declarables are available to templates in this module.


The set of components, directives, and pipes declared in this NgModule that can be used in the template of any component that is part of an NgModule that imports this NgModule. Exported declarations are the module's public API.


The set of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view.


The set of components that are bootstrapped when this module is bootstrapped. The components listed here are automatically added to entryComponents.


The set of schemas that declare elements to be allowed in the NgModule. Elements and properties that are neither Angular components nor directives must be declared in a schema.


A name or path that uniquely identifies this NgModule in getModuleFactory If left undefined, the NgModule is not registered with getModuleFactory.


When present, this module is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

Updated for Angular >=8 CLI For one component, use the following command:

ng generate component --skipTests=true component-name

For a single project, change or add the following in your angular.json:

  "projects": {
    "{PROJECT_NAME}": {
      "schematics": {
        "@schematics/angular:component": {
          "skipTests": true

For a global setting for all your projects, change or add the following in your angular.json:

  "schematics": {
    "@schematics/angular:component": {
      "skipTests": true

Or by using the command line

ng config schematics.@schematics/angular:component.skipTests true

For Angular < 8 Inside your angular-cli.json set the spec.component parameter to false:

   "defaults" : {
       "spec": {
           "component": false

or use the --spec=false option during creation

ng generate component --spec=false component-name