Prev Next

Web / Angular Interview questions

1. What is AngularJS? 2. What are the key features of AngularJS. 3. What are the advantages of using AngularJS? 4. What are the key components of AngularJS Framework? 5. What are the limitations of using AngularJS? 6. Explain about AngularJS Expression. 7. Can we pass parameters to an AngularJS controller? 8. What is bower? 9. What is a component in Angular? 10. What are .ts extension files? 11. How do you communicate between different modules of your application using angularjs? 12. How does interpolation, for example "{{ someModel }}" works? 13. What is $rootScope and how does it relate to $scope? 14. Advantages of components in AngularJS. 15. What is ngBind directive in AngularJS? 16. What is ngIf directive in Angular? 17. Difference between ng-show/ng-hide directives and ngIf in angularjs. 18. Explain directives in Angular. 19. What is the role of selector property of components in AngularJS? 20. Explain Angular architecture. 21. Type of module in Angular 2. 22. Explain root module in angular2. 23. What is an Angular module? 24. What does the npm start do? 25. How do I create a multiline template in the Angular component? 26. What is RXJS and how does it relate to Angular? 27. How to check if a variable is defined using ngIf in Angular? 28. How to check for multiple conditions using Angular ng-if? 29. Features of Angular2. 30. Explain ng-container in Angular. 31. Types of directives in Angular. 32. Difference between Directive and component in Angular. 33. Difference between ngOnInit and ngAfterViewInit of Angular2. 34. Difference between Constructor and ngOnInit in Angular. 35. What is a zone in Angular? 36. Can we use ngIf and ngFor on the same element in Angular? 37. What is router-link directive? 38. Difference between router-link and [router-link] with brackets. 39. Explain Hot Module Replacement (HMR). 40. What is webpack? 41. Difference between ng model and ng bind directives. 42. What is forRoot and forChild method in angular? 43. How do you create and register/provide service using ng CLI? 44. Difference between declarations, providers, and import in NgModule. 45. Explain pipes in Angular. 46. What is angular routing? 47. How to check the Angular version installed? 48. Explain the structure of Angular application projects. 49. What is angular CLI? 50. Elements of the Component decorator in Angular. 51. Explain Angular services. 52. How do I create a service as a singleton in Angular? 53. What is service worker and its advantages in Angular? 54. How does *ngIf directive works? 55. Difference between ng-class and ng-style directives. 56. Difference between Component and template/templateURL. 57. Default view encapsulation model in Angular. 58. What is Ivy in Angular? 59. Types of directives in Angular. 60. What are structural directives in Angular? 61. Difference between Structural and attribute directives. 62. What is <ng-template> in Angular? 63. Explain <ng-container> element in Angular. 64. Name a few builtin pipes in Angular that you are aware of. 65. What are the different types of Pipes in Angular? 66. What is JsonPipe? 67. What are the methods in Angular FormBuilder? 68. What is ngForm directive? 69. What are the child classes of AbstractControl? 70. Difference between Promises and Observable. 71. What is NGModule? 72. Can a Angular component be declared in multiple modules? 73. Design a game using Angular in which the user should click on the highlighted area to score before it vanishes. Also, it should display score with different levels like easy/medium/difficult. 74. What is tree shaking in Angular? 75. What defines an Angular view? 76. Difference between a view, a host view, and an embedded view. 77. Difference between createEmbeddedView and createComponent in Angular. 78. Various forms of data binding markup in Angular. 79. Is ngModel an attribute directive? 80. Mention a few roles of Services in Angular. 81. How do I make a parent component listen for child events? 82. What is the difference between CSS and SCSS? 83. What is router outlet in Angular? 84. What are angular guards? 85. Mention a few drawbacks (disadvantages) of using Angular. 86. What is Angular Universal or Angular SSR? 87. Explain index signature in typescript. 88. Can we consume SOAP web service with Angular Application? 89. Key features of IndexedDB. 90. What is Web worker in Angular? 91. How do you handle right-click event on a DIV in Angular? 92. How do you handle double-click in Angular? 93. What is a nested route in Angular? 94. Types of LocationStrategy in Angular routes. 95. Difference between RouterModule.forRoot() and forChild(). 96. What is APP_INITIALIZER in Angular? 97. Advantages of SCSS over CSS? 98. Why do we need to use Angular? 99. Difference between AngularJS vs Angular. 100. Types of Angular directives. 101. Explain the importance of NPM and node_modules folder? 102. What is the package.json file in Angular? 103. What is typescript and why do we need it? 104. What is schematics in Angular? 105. Explain the importance of Components and Modules? 106. What is Decorator in Angular? 107. What is metadata/annotation in Angular. 108. What is a template in Angular? 109. Different types of data binding in Angular. 110. What is SPA in Angular? 111. How to detect when an @Input() value changes in Angular? 112. What are PWAs? 113. What is the Jasmine test framework? 114. What is Setup and Teardown in Jasmine? 115. What is Karma in Angular testing? 116. What is the use of the Protractor framework in Angular? 117. Explain the purpose of SubSink in Angular. 118. What is NgRx? 119. Can we do two way binding without ngModel? If so, how? 120. What are HostListener and HostBinding? 121. Why using ElementRef is not recommended? 122. What is Angular Unit Testing? 123. How does code coverage work in angular 7? 124. What is single component Angular modules (SCAM)?
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. What is AngularJS?

AngularJS is a javascript framework used for creating single web page applications and dynamic web apps.

AngularJS is a structural framework that lets you use HTML as your template language and enables you extend HTML syntax to express your application components clearly and succinctly.

2. What are the key features of AngularJS.
  • Two Way Data-Binding,
  • Templates,
  • MVC,
  • Dependency Injection,
  • Directives,
  • Testing.
3. What are the advantages of using AngularJS?
  • AngularJS is a powerful JavaScript based framework that enables creating Single Page Application (SPA) and RICH Internet Application(RIA).
  • AngularJS applications are cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, free and used by many developers around the world. It is licensed under the Apache License version 2.0. https://www.madewithangular.com has the list of popular applications built with AngularJS.
  • AngularJS enables developers to write client side Javascript application using MVC (Model View Controller) pattern.

    Using AngularJS developers write less code and achieve more functionality.

  • AngularJS applications are unit testable.
  • AngularJS provides two-way data binding capability to HTML thus facilitating the users a rich and responsive experience.
  • AngularJS uses dependency injection and make use of separation of concerns. AngularJS helps creating reusable components.
4. What are the key components of AngularJS Framework?

The below 3 core directives forms the AngularJS framework.

  • ng-app − directive defines and links an AngularJS application to HTML.
  • ng-model − directive binds the AngularJS application data to HTML input controls.
  • ng-bind − binds the AngularJS Application data to HTML tags.
5. What are the limitations of using AngularJS?
  • AngularJS runs on the client side browser that make it quite obvious to compromise on the Application security. By minimizing the JS files in Production environment and leveraging other security measures, we could build better application security.
  • Client must enable JavaScript in the browser to run the AngularJS applications. Otherwise, the user will just see a blank page.
  • Memory leak in JavaScript can cause slow down of any browser. AngularJS works well only from Internet Explorer 8.0 onwards and doesn't support any older versions.
6. Explain about AngularJS Expression.

AngularJS expressions are code snippets that are usually placed in binding inside double braces such as {{ expression }}.

Expressions are used to bind application data to html. AngularJS expressions are pure javascript expressions and outputs the data where they are used.

7. Can we pass parameters to an AngularJS controller?

Yes. Using ng-init directive and a simple init function we can pass parameters to the AngularJS Controller.

8. What is bower?

Bower is a package manager for the web, Bower can manage AngularJS components that contain HTML, CSS, JavaScript, fonts or even image files.

Bower does not concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies.

9. What is a component in Angular?

Angular applications are made up of components. A component is the combination of an HTML template and a component class that controls a portion of the screen.

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

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'javapedia.net'; }

A component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.

10. What are .ts extension files?

They are TypeScript files, a superset of JavaScript. Angular uses TypeScript because its types make it easy to support developer productivity with tooling.

11. How do you communicate between different modules of your application using angularjs?

The below are the ways to communicate between modules of your application using core AngularJS functionality include,

  • Using services,
  • Using events,
  • By assigning models on $rootScope,
  • Directly between controllers, using $parent, $$childHead, $$nextSibling.
  • Directly between controllers, using ControllerAs, or other forms of inheritance.
12. How does interpolation, for example "{{ someModel }}" works?

It relies on $interpolation, a service called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a watch() is set. $interpolation returns a function, which has a single argument, "context". By calling that function and providing a scope as context, the expressions are $parse()-ed against that scope.

13. What is $rootScope and how does it relate to $scope?

$rootScope is the parent object of all $scope objected created in an angular application.

14. Advantages of components in AngularJS.
  • Simpler configuration than plain directives.
  • Promote sane defaults and best practices.
  • Optimized for component-based architecture.
  • Writing component directives will make it easier to upgrade to Angular 2.
15. What is ngBind directive in AngularJS?

The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.

16. What is ngIf directive in Angular?

ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively.

'then' template is the inline template of ngIf unless bound to a different value and 'else' template is blank unless it is bound.

17. Difference between ng-show/ng-hide directives and ngIf in angularjs.

ng-show/ng-hide will always insert the DOM element, but will display/hide it based on the condition. While ng-if will not insert the DOM element until the condition is not fulfilled.

18. Explain directives in Angular.

Angular directives are used to extend HTML and DOM elements's behavior. These are the special attributes, that start with ng- prefix, instructs Angular HTML compiler ($compile) to attach a specified behavior to that DOM element.

Examples of Angular inbuilt directives include ngApp, ngInit, ngBind ,ngModel and ngClass.

19. What is the role of selector property of components in AngularJS?

The selector property instructs the Angular to display the component inside a custom tag in the index.html.

@Component({
  selector: 'myApp',
  template: `<h1>Hi {{name}}</h1>`
})

In the above example, selector tells the Angular to display component inside the custom tag 'myApp'.

<myApp>Load Component content here ...</myApp>

20. Explain Angular architecture.

Angular architecture consists of 8 modules,

  • Module,
  • Component,
  • Template,
  • Metadata,
  • Data binding,
  • Service,
  • Directive,
  • and Dependency Injection.
21. Type of module in Angular 2.

There are 2 types, Root and feature modules. There is only one root module and many feature modules in an Angular application.

22. Explain root module in angular2.

Root module is an angular module class that describes how the application is assembled and the parts fitted together. The root module is usually named as AppModule.

Every angular application has at least one module, the root module to bootstrap and launch the application. There is only one root module for an angular application.

23. What is an Angular module?

A module groups and work as container for the different parts of application such as controllers, services, directives, pipes and so on.

24. What does the npm start do?

npm start command usually run 2 commands parallelly. 1 command watches for typescript file changes to refresh and the other for lite-server to load the index html file on the browser and refresh as required.

25. How do I create a multiline template in the Angular component?

Use backtick "`" instead of single quote.

26. What is RXJS and how does it relate to Angular?

RxJS is a library for reactive programming using Observables, to make it easier to compose asynchronous or callback-based code. Angular is built on top of RXJS.

27. How to check if a variable is defined using ngIf in Angular?

Check the variable against undefined keyword.

*ngIf= "dolRecords !== undefined" 

28. How to check for multiple conditions using Angular ng-if?

Use logical operator such as and (&&) to evaluate multiple conditions.

29. Features of Angular2.

Angular 2 is component based. Controllers and $scope are no longer in use and have been replaced by components and directives.

The specification for directives is considerably simplified and using @Directive annotation, a directive can be declared.

Improved dependency injection model in Angular2.

Use of TypeScript, a typed super set of JavaScript in Angular. The presence of types makes the code less prone to run-time errors.

TypeScript has generics and lambda feature.

With Angular 2 the Form Builder and Control Group are defined that makes it easy to build forms and it's validations .

30. Explain ng-container in Angular.

ng-container is a logical container used to group nodes but is not rendered in the DOM tree as a node.

ng-container can conditionally append a group of elements, using ngif in your application, it eliminates the need to wrap them with another element.

 <ng-container *ngIf="true">
        <h2>Title</h2>
      
 </ng-container>

31. Types of directives in Angular.

There are 3 types.

  • Component,
  • Attribute Directive,
  • and Structural.
32. Difference between Directive and component in Angular.

Directives associate behavior to elements in the DOM, consisting of Structural, Attribute and Component types.

Components are a type of directive in Angular that allows utilizing web component functionality - encapsulated, reusable elements available throughout our application.

The main difference between a component and a directive is that a component has a template, while an attribute or structural directive does not have a template.

33. Difference between ngOnInit and ngAfterViewInit of Angular2.

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

ngAfterViewInit is also a lifecycle hook that is called after a component's view has been fully initialized.

34. Difference between Constructor and ngOnInit in Angular.

The Constructor of the class is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better DI analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor.

ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.

35. What is a zone in Angular?

A Zone is an execution context that persists across async tasks and allows the creator of the zone to observe and control execution of the code within the zone.

These execution contexts allow Angular to track the start and completion of asynchronous activities and perform tasks as required (for example, change detection).

36. Can we use ngIf and ngFor on the same element in Angular?

No, Angular2 does not support more than one structural directive on the same element.

You may use the element that allows you to use separate elements for each structural directive in a nested format.

37. What is router-link directive?

The RouterOutlet directive tells our router where to render the content in the view.

38. Difference between router-link and [router-link] with brackets.

Use brackets to pass a bindable property (a variable).

39. Explain Hot Module Replacement (HMR).

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development process.

40. What is webpack?

webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into one or more bundles.

41. Difference between ng model and ng bind directives.

'ng-model' is an angular directive used for achieving two-way data binding. Any modifications to that model from the Scope/Controller will be automatically propagated to the view regardless of whether the view is asking for the updated data and any modifications to that model from the View will be immediately reflected back to the Scope/Controller.

'ng-bind' is an angular directive used for achieving one-way data binding. After the binding, any modifications to that model from the scope/controller will be automatically propagated to the view regardless of whether the view is asking for the updated data. No propagation happens for any change to the model from the view to the controller.

42. What is forRoot and forChild method in angular?

The forRoot is a static method and it helps to configure the modules. For example, RouterModule.forRoot.

The RouterModule also has forChild method, static method used to configure the routes of lazy-loaded modules. The forRoot and forChild are the traditional names for methods that configure services in root.

43. How do you create and register/provide service using ng CLI?

It is possible to provide the service when creating the service. When you create the service using NG CLI specify the module using (--module or -m) to provide as shown below.

ng g s KenoDataService --module=app.module

44. Difference between declarations, providers, and import in NgModule.

imports makes the exported declarations of other modules available in the current module.

declarations make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.

providers make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as the dependency.

45. Explain pipes in Angular.

Angular pipes is a way to write display-value transformations that you can declare in your HTML.

A pipe takes in data as input and transforms it into the desired output. In the below example, pipe transforms a component's birthday property into a human-friendly date.

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

@Component({
  selector: 'app-birthday',
  template: `<p>The User's birthday is {{ birthday | date }}</p>`
})
export class UserBirthdayComponent {
  birthday = new Date(1981, 3, 15); 
}

46. What is angular routing?

The Angular Router enables navigation from one view to the other as users perform application tasks.

Angular router interpret a browser URL to navigate to a client-generated view. It also can pass parameters along to the supporting view component that help it decide dynamic content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link.

47. How to check the Angular version installed?

For angular 4+, use one of the below commands.

  • ng version,
  • ng -v.
48. Explain the structure of Angular application projects.

For instance, take the structure of the Shopper Stop angular application.

e2e folder holds end to end test cases that help ensure the angular components are working correctly. This subfolder stores configuration and source files for a set of end-to-end tests that correspond to angular application.

node_modules subfolder provides/stores the npm packages required for the application.

src subfolder contains the source files related to app logic, data, and assets, along with configuration files for the initial application.

.editorconfig configuration file stores editor configuration.

.gitignore file specifies untracked files that Git should ignore.

angular.json stores CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses.

package-lock.json provides version information for all packages installed into node_modules by the npm client.

package.json configures npm package dependencies that are available to all projects in the workspace.

README.md contains introductory documentation.

tsconfig.json has default TypeScript configuration for apps in the workspace, including TypeScript and Angular template compiler options.

tslint.json stores default TSLint configuration for apps in the workspace.

Structure of src sub-folder.

app/ contains the component files in which your app logic and data are defined.

assets/ contains image files and other asset files to be copied as-is when you build your application.

environments/ contains build configuration options for particular target environments. By default, there is an unnamed standard development environment and a production ("prod") environment. You can define additional target environment configurations.

browserlist configures sharing of target browsers and Node.js versions among various front-end tools.

favicon.ico is the icon to use for this app in the bookmark bar.

index.html is the main HTML page that is served when someone visits your angular site.

main.ts is the main entry point for your app. This typescript file compiles the application with the JIT compiler and bootstraps the application's root module (AppModule) to run in the browser.

polyfills.ts provides polyfill scripts for browser support.

styles.sass lists CSS files that supply styles for a project. The extension reflects the style preprocessor you have configured for the project.

test.ts is the main entry point for your unit tests, with some Angular-specific configuration.

tsconfig.app.json inherits from the workspace-wide tsconfig.json file.

tsconfig.spec.json inherits from the workspace-wide tsconfig.json file.

tslint.json inherits from the workspace-wide tslint.json file.

49. What is angular CLI?

Angular CLI is a command line interface to scaffold and build angular apps. It provides a scalable project structure and also handles most of the task in building the application.

Angular CLI comes with a handful of commands to set up and build your project from scratch. Below are few commands.

ng new "path_to_project" will create a new project by installing required dependencies.

ng serve builds your project and also it runs the project on the local server.

ng help provides the list of ng commands for reference.

50. Elements of the Component decorator in Angular.

The Component decorator is an object with many properties such as,

selector specifies the tag (html identifier) used to call this component in HTML templates as any standard HTML tags.

templateUrl specifies HTML template path used to display this component. Alternatively template parameter may be used to include the HTML template inlined as a string.

styleUrls: specifies an list of URLs for CSS style-sheets for the component.

import { Component } from  '@angular/core';
@Component({
    selector:  'app-search',
    templateUrl:  './app.component.html',
    styleUrls: ['./app.component.css']
})
export  class  AppComponent {
    title  =  'Shoppers-stop';
}

51. Explain Angular services.

Services are a great way to share information among components/classes that don't know each other. Services can be injected into any component and it usually holds data/code providing data for one or more components.

To create a service using angular CLI, use the below command.

ng g service searchAPI

The above command generates 2 files, search-api.service.ts, and search-api.service.spec.ts, hold the code related to service and unit test specification for the service respectively.

search-api.service.ts file generated content follows:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SearchAPIService {

  constructor() { }
}
52. How do I create a service as a singleton in Angular?

We can create a service as singleton in Angular in 2 ways:

  • Declare that the service should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator as shown below. This is the preferred way to create a singleton service starting Angular 6.

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class UserService {
    }
    
  • Include the service in the AppModule or in a module that is only imported by the AppModule.
53. What is service worker and its advantages in Angular?

Service worker is a script that runs in a web browser and manages cache of any web application. Angular applications are turned into progressive web application (PWA) after implementing service worker there by benefitted by,

  • increased reliability and performance,
  • eliminate additional low level coding for caching,
  • optimize the end user experience on application over a slow network connection,
  • minimize the risk of serving outdated content.
54. How does *ngIf directive works?

ngIf directive does not show or hide an element from DOM. Instead, the ngIf directive removes or recreates a portion of the DOM tree based on the ngIf {expression}. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise, a clone of the element is reinserted into the DOM.

Angular translates the *ngIf attribute into a <ng-template> element, wrapped around the host element. For example, consider the below code snippet.

<div *ngIf="employee" >{{employee.name}}</div>

This code will be translated as shown below by Angular.

<ng-template [ngIf]="employee">
  <div>{{employee.name}}</div>
</ng-template>
55. Difference between ng-class and ng-style directives.

ng-style is used to interpolate javascript object into style attribute.

ng-style="{width: 10px}"

The above directive will be translated to style="width:10px".

ng-class directive translates your object into class attribute.

ng-class="{'highlight-class': isActive}"

The above template is translated to class="highlight-class" when isActive variable is true.

56. Difference between Component and template/templateURL.

In Angular as compared to MVC, a component acts as a controller/ViewModel while template represent the "view".

57. Default view encapsulation model in Angular.

Emulated view encapsulation is the default encapsulation that emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view.

58. What is Ivy in Angular?

Ivy is the code name for Angular's next-generation compilation and rendering pipeline. With the version 9 release of Angular, the new compiler and runtime instructions are used by default instead of the older compiler and runtime, known as View Engine.

59. Types of directives in Angular.

There are 3 types of directives in Angular:

Components, directives with a template.

Structural directives, changes the DOM layout by adding and removing DOM elements. Examples are NgFor and NgIf.

Attribute directives, changes the appearance or behavior of an element, component, or another directive. Examples are NgStyle and NgClass.

60. What are structural directives in Angular?

Structual directives are responsible for HTML Layouts, reshaping DOM structure by dynamically adding and removing/manipulating elements.

Structural directives have *(asterisk) preceding the attribute name and no square brackets nor parenthesis. This makes structural directives easy to identify.

Examples for structural directives are as follows.

  • *ngIf,
  • *ngFor,
  • ngSwitch (*ngSwitchCase and *ngSwitchDefault).
61. Difference between Structural and attribute directives.
Structural directive.Attribute directive.
Structural directives are responsible for HTML layout. They shape and modify the DOM's structure by adding, removing, or manipulating elements. .Attribute directive are used as element attributes that change the appearance or behavior of an element, component, or another directive. .
You can only apply one structural directive to a host element.You can apply many attribute directives to one host element.
*ngIf and *ngFor are examples.ngStyle and ngClass are builtin attribute directives.
62. What is <ng-template> in Angular?

The <ng-template> is an angular element for rendering HTML. It will never get displayed directly in the view. Before rendering the view, Angular replaces the <ng-template> and its contents with a comment.

63. Explain <ng-container> element in Angular.

The Angular <ng-container> is a grouping element that does NOT interfere with styles or layout because Angular doesn't put this element in the DOM.

The <ng-container> is a syntax element recognized by the Angular parser. It is not a directive, component, class, or interface. This element can replace a span tag as you may want to eliminate any styles associated with the span element, also ng-container can be used for conditional select-option list. In short, use <ng-container> as a grouping element when there is no suitable host element.

64. Name a few builtin pipes in Angular that you are aware of.

Angular comes with builtin pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.

65. What are the different types of Pipes in Angular?

There are 2 types of pipes: pure and impure. Pipes are pure by default. You make a pipe impure by setting its pure flag to false.

@Pipe({
  name: 'exponential',
  pure: false
})

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value such as String, Number, Boolean, Symbol or a changed object reference like Date, Array, Function or Object.

Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, even for every keystroke or mouse movement. Implement an impure pipe with great care since an expensive, long-running pipe could affect performance and user experience.

66. What is JsonPipe?

JsonPipe is an inbuilt pipe that converts a value/object into its JSON-format representation. It is usually used for debugging.

{{ value_expression | json }}

<form [formGroup] = "profileForm" >
  <label>
First Name: <input type="text" formControlName = "firstName"></label>
<label>Last Name: <input type="text" formControlName ="lastName"></label>

<div formGroupName="address">
<h4>Address</h4>
<label>Street:
<input type="text" formControlName = "street">
</label>
<label>City:
<input type="text" formControlName="city">
</label>
<label>State:
  <input type="text" formControlName="state">
  </label>
  <label>Zip:
    <input type="text" formControlName="zip">
  </label>

</div>
  
<button type="submit" (click)="onsubmit()" [disabled]="!profileForm.valid"> Submit</button> 
</form>
 {{profileForm.value}}

 {{profileForm.value | json }}

67. What are the methods in Angular FormBuilder?

The FormBuilder service is an injectable provider that is provided with the reactive forms module.

The FormBuilder service has 3 methods: control(), group(), and array(). These are factory methods for generating instances in your component classes including form controls, form groups, and form arrays.

68. What is ngForm directive?

The NgForm directive powers the form element with additional features. It holds the controls you created for the elements with a ngModel directive and name attribute, monitors their properties and its validity.

<form  #myForm="ngForm">

You must define name attribute when using [(ngModel)] in combination with a form.

69. What are the child classes of AbstractControl?

AbstractControl is the base class for FormControl, FormGroup, and FormArray.

70. Difference between Promises and Observable.

Promise.Observable.
A Promise handles only one event when an async operation completes or fails.An Observable is like a Stream and accepts 0 or more (multiple) events where the callback is called for each event.
Promise doesn't support cancelation.Observables are cancelable.
Promises execute immediately on creation.Observables are declarative and computation does not start until subscription.
Promises provide only one value.Observables provide many values.
Promises push errors to the child promises for error handling. Observables subscribe() is responsible for handling errors that provides centralized and predictable error handling.
71. What is NGModule?

An NgModule describes how the application components fit together. Every application has at least one Angular module, the root module that you bootstrap to launch the application. By convention, it is usually called AppModule.

The @NgModule decorator identifies AppModule as an NgModule class. @NgModule takes a metadata object that tells Angular how to compile and launch the application.

Reference: Angular IO docs.

72. Can a Angular component be declared in multiple modules?

No. A component can be declared only in one module and that module be reused by importing it.

73. Design a game using Angular in which the user should click on the highlighted area to score before it vanishes. Also, it should display score with different levels like easy/medium/difficult.

pleae find the game app in stackbliz.

74. What is tree shaking in Angular?

Tree shaking is a step as part of the build process in which eliminates/drops code in your project that are not used/referenced anywhere.

75. What defines an Angular view?

A Angular components and its HTML template together defines an Angular view

76. Difference between a view, a host view, and an embedded view.

Each component along with its template in Angular is represented as a view.

The embedded view is a view that is created for the view nodes specified in the ng-template. It's like a component view but it doesn't have a wrapper component element and component data like injector

77. Difference between createEmbeddedView and createComponent in Angular.

createEmbeddedView is used to create a view using TemplateRef. TemplateRef is created by Angular compiler when it encounters ng-template tag in your component HTML. The view created using this method is called an embedded view.

createComponent is used to create a view using ComponentFactory. It is created by Angular compiler when you specify a component in the bootstrap property of the module so that compiler generates a factory for it. The view created using this method is called a host view.

import { Component, ViewContainerRef, ComponentFactoryResolver, NgZone, VERSION, ViewChild } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `<h1>Hello world!</h1>`,
  styles: [``]
})
export class HelloWorldComponent  {}

@Component({
  selector: 'my-app',
  template: `
      <ng-container #hw></ng-container>
  `,
  styles: ['']
})
export class AppComponent {

  @ViewChild('hw', {read:ViewContainerRef}) vc: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {}

  ngOnInit() {
    const factory = this.resolver.resolveComponentFactory(HelloWorldComponent);
    this.vc.createComponent(factory);
  }
}

78. Various forms of data binding markup in Angular.

There are 4 forms.

  • {{value}},
  • [property]="value",
  • (event)="handler",
  • [(ng-model)] ="property".
79. Is ngModel an attribute directive?

Yes. ngModel modifies the behavior of an existing element by setting its display value property and responding to change events.

80. Mention a few roles of Services in Angular.

Service fetch data from server, also it can be used to validate user inputs.

81. How do I make a parent component listen for child events?

The parent component may bind to the EventEmitter property of child that emit events and react to those events.

The child's EventEmitter property is an output property decorated with @Output().

82. What is the difference between CSS and SCSS?

CSS is the styling language that any browser understands to style webpages.

SCSS is a special type of file for SASS, a program written in Ruby that assembles CSS style sheets for a browser. SASS adds lots of additional functionality to CSS like variables, nesting and more which can make writing CSS easier and faster. SCSS files are processed by the server running a web app to output a traditional CSS that your browser can understand.

83. What is router outlet in Angular?

The RouterOutlet is a directive from the router library used as a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet.

<router-outlet></router-outlet>
<!-- Routed components displayed here -->

84. What are angular guards?

Guards in Angular are like components that gets executed before the route is loaded or the ones leaving the route. Guards help protect the route.

85. Mention a few drawbacks (disadvantages) of using Angular.
  • Steep learning curve required.
  • Performance may be concern in complex SPA applications.
  • Limited SEO options and less accessibility for search engine crawlers.
86. What is Angular Universal or Angular SSR?

Angular Universal also known as Angular SSR (Server side rendering) is a technology that renders Angular applications on the server.

A regular Angular application executes in the browser, rendering pages in the DOM in response to user actions. However Angular Universal executes on the server, generating static application pages that later get bootstrapped on the client.

With angular universal, the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.

Advantages of using Angular universal.

  • Facilitate web crawlers through search engine optimization (SEO).
  • Improve performance on mobile and low-powered devices.
  • Show the first page quickly with a first-contentful paint (FCP).
87. Explain index signature in typescript.

Index signatures are used to define objects that is used as dictionaries.

interface KeyMap {
  [key: string]: number;
} 

keyMap: KeyMap = {};

keyMap['key1'] = 4;
88. Can we consume SOAP web service with Angular Application?

Yes. ngx-soap npm library we can access SOAP web services using Angular application.

ngx-soap is a simple SOAP client for Angular 6/7.

1. install ngx-soap and dependencies

npm install --save ngx-soap

npm install --save buffer concat-stream core-js crypto-js events lodash sax stream uuid

2. Add NgxSoapModule to your app module.

import { NgxSoapModule } from 'ngx-soap';
...
    @NgModule({
        imports: [ ..., NgxSoapModule, ... ]
    ...

3. Inject NgxSoapService in your component/service:

...
import { NgxSoapService, Client, ISoapMethodResponse } from 'ngx-soap';
...

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    client: Client;
    intA = 2;
    intB = 3;
    
    constructor(private soap: NgxSoapService) {
        this.soap.createClient('assets/calculator.wsdl').subscribe(client => this.client = client);
    }
    
    sum() {
        const body = {
          intA: this.intA,
          intB: this.intB
        };
        (<any>this.client).Add(body).subscribe((res: ISoapMethodResponse) => this.message = res.result.AddResult);
    }
}

89. Key features of IndexedDB.
  • IndexedDB databases store key-value pairs.
  • IndexedDB is built on a transactional database model.
  • The IndexedDB API is asynchronous.
  • IndexedDB uses DOM events to notify you when results are available.
  • IndexedDB is object-oriented.
  • IndexedDB does not use Structured Query Language (SQL) and adheres to same origin policy.
90. What is Web worker in Angular?

Web workers allow you to run CPU-intensive computations in a background thread, freeing the main thread to update the user interface. If you find your application performs a lot of computations, such as image processing, looped mathematical calculations, using web workers can help increase your application's performance.

91. How do you handle right-click event on a DIV in Angular?

Use the "contextMenu" handler as shown in the below code.

<div (contextmenu)="onrightClick($event)">right click me!</div>

92. How do you handle double-click in Angular?

Use dblclick event handler.

<a (click)="method1()" (dblclick)="method2()">

93. What is a nested route in Angular?

In a real-world complex application, you may want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second < router-outlet> to your app because it is in addition to the in the root component.

A child route is like any other route, in that it needs both a path and a component. The one difference is that you place child routes in a children array within the parent route.

const routes: Routes = [
  {
    path: 'first-component',
    component: FirstComponent, // this is the component with the <router-outlet> in the template
    children: [
      {
        path: 'child-a', // child route path
        component: ChildAComponent, // child route component that the router renders
      },
      {
        path: 'child-b',
        component: ChildBComponent, // another child route component that the router renders
      },
    ],
  },
];

94. Types of LocationStrategy in Angular routes.

The router supports both styles with two LocationStrategy providers.

  • PathLocationStrategy, the default "HTML5 pushState" style, a LocationStrategy used to configure the Location service to represent its state in the path of the browser's URL. The RouterModule.forRoot() function sets the LocationStrategy to the PathLocationStrategy, which makes it the default strategy.
  • HashLocationStrategy, the "hash URL" style, a LocationStrategy used to configure the Location service to represent its state in the hash fragment of the browser's URL.
95. Difference between RouterModule.forRoot() and forChild().

There are two methods we can invoke using RouterModule in order to register routes: forRoot, and forChild.

The forRoot() method creates a NgModule that contains all the directives, the given routes, and the Router service itself.

The forChild() method creates a NgModule that contains all the directives and the given routes but does not include the Router service. In order to register nested routes in a lazy-loaded module, we will need to use the forChild.

96. What is APP_INITIALIZER in Angular?

APP_INITIALIZER register listeners for the Angular bootstrap process which serves as hooks during Application initialization. This way we can use such hooks to subscribe to the application bootstrap process and perform our initialization logic.

The APP_INITIALIZER is an instance of InjectionToken. It is a built-in Injection token provided by Angular.

The Angular will execute the function provided by this token when the application loads. If the function returns the promise, then the angular will wait until the promise is resolved. This will make it an ideal place to perform some initialization logic before the application is initialized.

97. Advantages of SCSS over CSS?

SCSS is full of advanced features, SCSS offers variables which you can use to shorten your code. It is a great advantage over conventional CSS.

SCSS adds the feature of @import which lets you import your customized SCSS files.

98. Why do we need to use Angular?

Angular is a JavaScript Binding framework that binds the HTML UI and Javascript Model. This helps you to reduce your effort on writing those long lines of code for binding.

Angular helps you to build SPA by using the concept of routing. It also has lots of other features like HTTP, DI, Input(), Output() using which we don't need any other frameworks.

99. Difference between AngularJS vs Angular.
AngularJSAngular
Versions(1.x)2, 4, 5, 6,7,8, 9 and 10
LanguageJavaScriptTypeScript
ArchitectureControllerComponent
Mobile compliantNoYes
CLINoYes
Lazy loadingNoYes
SEONoYes
Server sideNoYes

100. Types of Angular directives.

The different types of Angular directives are as follows:

  • Components- directives with a template. This type of directive is the most common directive type.
  • Attribute directives- directives that change the appearance or behavior of an element, component, or another directive.
  • Structural directives- directives that change the DOM layout by adding and removing DOM elements.

101. Explain the importance of NPM and node_modules folder?

NPM is a package manager which makes the installation of JavaScript framwork and packages easy.

"node_modules" is the folder where the packages are installed.

102. What is the package.json file in Angular?

package.json file has all the JavaScript references needed for a project. So rather than installing one package at a time we can install all packages in one go.

103. What is typescript and why do we need it?

Typescript is a superset of Javascript and adds types to the language. It gives a nice Object-oriented programming environment which transpiles/converts to JavaScript.It is strongly typed so we will have less type errors.

104. What is schematics in Angular?

A schematic is a template-based code generator that supports complex logic. It is a set of instructions for transforming a software project by generating or modifying code. Schematics are packaged into collections and installed with npm.

105. Explain the importance of Components and Modules?

Components is where you write your binding code. Module logically groups components.

106. What is Decorator in Angular?

Decorator defines what kind of Angular class is it. For example, if you decorate "@Component" then it says the class is an Angular component, if you specify as "@NGModule" it becomes Angular module.

107. What is metadata/annotation in Angular.

This is nothing but Angular decorators such as @Component and @NgModule.

108. What is a template in Angular?

Template is an HTML view of Angular in which we can write directives. There are 2 ways of defining template, inline and separate HTML file.

109. Different types of data binding in Angular.

There are 4 types.

  • expression/Interpolation binding {{}}, for example {{cust.customerName}}
  • property binding [], [(ngModel)] = "cust.customerId"
  • event binding (), for example, (click) = "toggle()"
  • two way binding [()] , in this case, data from controller to view is passed and on event data move from view to controller.
110. What is SPA in Angular?

SPA stands for Single Page Application.

Single Page Application are applications where the main UI gets loaded once and then the needed UI is loaded on demand.

111. How to detect when an @Input() value changes in Angular?

Actually, there are two ways of detecting and acting upon when an input changes in the child component in angular.

  • Use the ngOnChanges() lifecycle method.
  • Use input property setter.
  @Input() categoryId: string;
        
    ngOnChanges(changes: SimpleChanges) {
        
        this.doSomething(changes.categoryId.currentValue);
        // You can also use categoryId.previousValue and 
        // categoryId.firstChange for comparing old and new values
        
    }

112. What are PWAs?

Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.

PWAs provide a number of advantages to users - including being installable, progressively enhanced, responsively designed, re-engageable, linkable, discoverable, network independent, and secure.

113. What is the Jasmine test framework?

Jasmine is a JavaScript testing framework that supports a software development practice called Behaviour-Driven Development, or BDD for short. It’s a specific flavour of Test-Driven Development (TDD).

Jasmine, and BDD in general, attempts to describe tests in a human-readable format so that non-technical people can understand what is being tested. However, even if you are technical reading tests in BDD format makes it a lot easier to understand what’s going on.

For example, to test the below function:

function helloWorld() {
  return 'Hello world!';
}

describe('Hello world', () => { 
  it('says hello', () => { 
    expect(helloWorld()) 
        .toEqual('Hello world!'); 
  });
});

114. What is Setup and Teardown in Jasmine?

Sometimes in order to test a feature we need to perform some setup, perhaps it's creating some test objects. Also, we may need to perform some cleanup activities after we have finished testing, perhaps we need to delete some files from the hard drive.

These activities are called setup and teardown (for cleaning up) and Jasmine has a few functions we can use to make this easier:

beforeAll function is called once, before all the specs in a test suite (describe function) are run.

afterAll function is called once after all the specs in a test suite are finished.

beforeEach function is called before each test specification (it function) is run.

afterEach function is called after each test specification is run.

describe('Hello world', () => {

  let expected = "";

  beforeEach(() => {
    expected = "Hello World";
  });

  afterEach(() => {
    expected = "";
  });

  it('says hello', () => {
    expect(helloWorld())
        .toEqual(expected);
  });
});

115. What is Karma in Angular testing?

Karma is a task runner for our tests. It uses a configuration file in order to set the startup file, the reporters, the testing framework, the browser among other things.

116. What is the use of the Protractor framework in Angular?

Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.

117. Explain the purpose of SubSink in Angular.

SubSink help manage multiple subscriptions. SubSink is a simple class to absorb RxJS subscriptions in an array. Call unsubscribe() to unsubscribe all of them, as you would do in your component library's unmount / onDestroy lifecycle event.

private subscriptions = new SubSink();

  ngOnInit() {
    // Method 1
    this.subscriptions.add(this.userService.getAllUsers().subscribe(data => {
      this.userList = data;
      this.userListSubject$.next(this.userList);
    }));

    // Method 2
    this.subscriptions.sink = this.userService.getAllUsers().subscribe(data => {
      this.userList = data;
      this.userListSubject$.next(this.userList);
    });
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }

118. What is NgRx?

NgRx is a framework for building reactive applications in Angular. NgRx provides libraries for:

  • Managing global and local state.
  • Isolation of side effects to promote a cleaner component architecture.
  • Entity collection management.
  • Integration with the Angular Router.
  • Developer tooling that enhances developer experience when building many different types of applications.

119. Can we do two way binding without ngModel? If so, how?

<input [value]="title" (input)="title=$event.target.value">

120. What are HostListener and HostBinding?

@HostListener() function decorator allows you to handle the events of the host element in the directive class.

@HostBinding() function decorator allows you to set the properties of the host element.

121. Why using ElementRef is not recommended?

Permitting direct access to the DOM can make your application vulnerable to XSS attacks.

Direct access to native elements is not supported in the case of web workers.

122. What is Angular Unit Testing?

Angular Unit Testing is used to test individual components of the applications. It is performed by using Karma and Jasmine. Jasmine is used in writing the tests and Karma is used in running those tests. We can use Async and TestBed in testing Asynchronous Code, Components, Directives and Service easier.

123. How does code coverage work in angular 7?

The CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.

To generate a coverage report run the following command in the root of your project.

ng test --code-coverage

When the tests are complete, the command creates a new /coverage folder in the project. Open the index.html file to see a report with your source code and code coverage values.

If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, angular.json:

"test": {
  "options": {
    "codeCoverage": true
  }
}

124. What is single component Angular modules (SCAM)?

SCAMs (single component Angular modules) are Angular modules that are scoped to a single declarable. For directives and pipes, they declare and export a single declarable.

«
»
ReactJS

Comments & Discussions