Angular Interview Questions

Wouldn't it be great if you knew the types of interview questions a hiring manager would be asking you in your next Angular JS interview? Prepare better with the top AngularJS interview questions and answers which will hone your core interview skills and help you outperform your peers.

  • 4.7 Rating
  • 20 Question(s)
  • 23 Mins of Read
  • 6607 Reader(s)

Advanced

We can simply use the index keyword. For example, in the following code, all we are doing is add let i = index in the ngFor expression and we can then access the index of the current element in the loop using the variable name - i.

<tr *ngFor="let policy of policies; let i = index">
     <td>Index: {{i}}</td>
     <td>{{policy.name}}</td>
</tr>

The ngIf directive gets a nice improvement in Angular version 4.0.0.  Earlier, in order to simulate if-then-else blocks in Angular templates, we had to use two ngIf directives with opposed boolean conditions. In Angular version 4 and higher we now get an “else” instruction as part of the ngIf directive. Here is an example.

<div *ngIf="isLoggedIn(); else notLoggedIn">
     Hi, {{ user.name }}!
</div>
<ng-template #notLoggedIn>
     You're not logged in.
</ng-template>

In the above code, the else keyword is used to specify the name of a template variable that will be used to render a template only if the if-condition fails to match. Simple, right?

A routing module is required if the application consists of multiple components and URLs and the user is expected to navigate from one component to another. The job of the Routing Module is to  interpret the browser's URL as an instruction to load a specific component along with its view. The application has a main router configured and bootstrapped. This is done by passing an array of routes to RouterModule.forRoot(), and since this returns another module, it has to be added to the imports meta property in the main application module.

The RouterModule

  • Keeps all our routing concerns separate from our feature module.
  • makes the code much more understandable and manageable.
  • provides a module to replace or remove when testing our feature module.
  • provides a common place for required routing service providers including guards and resolvers.
  • is not concerned with feature module declarations and does not lead to any conflicts.

Two components in Angular need to have a parent-child relationship if they want to communicate directly with each other. In some cases, having a common parent for two components is also a solution to allow the two child components to be able to communicate. Commonly the following two methods are used.

  • Parent/child communication using @Input decorator and @Output decorator with EventEmitter
  • Communication using services and Angular dependency injection system.

The second method can be used to perform communication between any two components in the app. They do not need to share a parent-child relationship. They use a service (which is a singleton class) to send and receive data from each other.

Services are singleton classes that are instantiated only once throughout the lifecycle of the application. Since these classes can only be instantiated once, there can only be one instance alive at all times. We can use this to share data between components. We can set the values of data members in the service class from one component and can access the values of those data members from other components. Since both the components classes are accessing the only instance, it results in sharing of the information between components.

A lean component is a component which have the sole purpose to display or present data to user. Lean components delegate data fetching, business logic, input validation etc. to other classes like models, services, redux effects/actions etc. Lean component follows single responsibility principle and they receive the data as an input from outside the component and present it to the user as specified in the component template..

They receive the data that they need to display and then present the data to the user in the specified templated formatting.

The following is an example component, the user profile component.

<user-profile [user]="user"></user-profile>

The component takes an object user and the rest of the job of the component is to display the data to the user in a nice and clean UI. The component does not deal with any other business logic or computations in the app.

@ViewChild decorator is used to search for an element inside the component’s template. It makes it very easy to get a reference to a child component from the template. The parameter that we pass as the first argument to the ViewChild is the type of the component or the reference we want to search for, in the template. If more than one elements match the queried elements, it returns us the first one that it found. @ViewChild returns a reference of an element so, we can use ElementRef to define the type of variable.

To get references to multiple children components we can use @ViewChildren() decorator. It returns a QueryList object that is an array of the references to the matches elements in the template.

Example: Consider the following HTML snippet in a component.

<some-component #someVariable></some-component>

To get a reference to the component in the component class, we can use @ViewChild. All we need to do is,

@ViewChild('someVariable') something;

Similarly, if you want to get access to all the elements of the page that have certain type, you can do that using,

@ViewChildren(someType) somethings;

This returns a QueryList which is an array of the references to all the matching elements.

To understand the difference between the ViewChild and ContentChild decorators, you first need to understand the differences between the Shadow DOM and light DOM. Also, think of yourself as the creator of a component that other developers will use in their applications.

Shadow DOM is an internal DOM of your component that is defined by the creator of the component and hidden from the end-user or the developer using the component.

For example,

@Component({
   selector: 'some-component',
   template: `
   <h1>I am Shadow DOM!</h1>
     <h2>Nice to meet you :)</h2>
     <ng-content></ng-content>
   `;
})
class SomeComponent { /* ... */ }

Light DOM is the DOM/content that is projected into the component by the developer or the user of the component.

For example,

@Component({
   selector: 'another-component',
   directives: [SomeComponent],
   template: `
     <some-component>
       <h1>Hi! I am Light DOM!</h1>
       <h2>So happy to see you!</h2>
     </some-component>
   `
})
class AnotherComponent { /* ... */ }

The difference between @ViewChildren and @ContentChildren is that @ViewChildren looks for elements in Shadow DOM while @ContentChildren looks for them in Light DOM. Both of them return the references to the queried elements.

NgFor and NgIf cannot be used together on the same element. However, there is a workaround that allows you to achieve the results that you generally intend to get by using these two directives together. You can use an ng-container component. Look at the example code below.

<some-component>
     <ng-container *ngFor="let task of tasks">
         <p *ngIf="task.Status == ‘done’">{{task.Title}}</p>
     </ng-container>
</some-component>
<ng-container> 

is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node. <ng-container> is rendered as an HTML comment.

Like any other OOP language, for example JAVA, C# etc., a constructor is a special named function within a class. The constructor is called when the class in instantiated. It is out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component.

By adding the ngOnInit lifecycle hook, Angular fires a method once it has finished setting the component up, and the hook is part of the component’s lifecycle.

ngOnInit is purely there to give us a signal that Angular has finished initialising the component and we can hook any code that we want executed in the ngOnInit function.

When you are developing an Angular app that is constantly growing in size and needs to be managed very well, you may not want to write the same pieces of code in multiple components. In these cases, it is a good practice to write the common logic in a service and use it from different components as and when required. 

Components generally do not fetch or save data from the web resource or the API and they certainly shouldn't knowingly present fake data. They are supposed to focus on presenting data and delegate data access, like fetching and saving, to a service.

Services are also used majorly for sharing data between different components. Since services are singleton classes, which simply means that they can only be instantiated once throughout the lifecycle of the app, only one instance of a service lives at all times. This can be used to share data between components since all the components have the access to the single instance of the service class.

To create a service in Angular, you can use the Angular CLI command.

ng generate service <service-name>

The separation of concerns is the main reason why Angular services came into existence. Every service annotates the class with the @Injectable() decorator. This makes the class able to participate in the dependency injection system.

NgModule is a special decorator that marks a TS class as an Angular Module. You can think of an Angular module as a logical chunk of code that is delegated a responsibility. An NgModule class describes how the application parts fit together. 

Every application has at least one NgModule, the root module that we bootstrap to launch the application.

@NgModule accepts a metadata object that tells Angular how to compile and launch the application. The properties are:

imports – External or internal modules that the application needs or depends on to run, like the BrowserModule that every application needs to run in a browser.

declarations – the application's components, which belongs to the NgModule class. We must declare every component in an NgModule class. If we use a component without declaring it, we'll see a clear error message in the browser’s console.

bootstrap – the root component that Angular creates and inserts into the index.html host web page. The application will be launched by creating the components listed in this array.

exports - exports is an array of components that are made available to other modules from within this module. In a way, exported classes are made available to the outside world.

providers - is also an array and contains the list of all the services and injectables.

Simply put, the AsyncPipe allows us to render asynchronous data.

The async pipe subscribes to an Observable or Promise and returns the latest value as emitted by the promise or observable. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable. AsyncPipe accepts as argument an observable or a promise, calls subscribe or attaches a then handler, then waits for the asynchronous result before passing it through to the caller.

Consider the following example.

my-component.html

<span>Wait for it... {{ greeting | async }}</span>
my-component.ts
export class MyComponent {
   greeting: Promise<string>|null = null;
   constructor() { 
this.reset(); 
}
reset() {
     this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; 
});
  }

In the above example, the greeting property is not available immediately to the template and thus rendering it out can lead to unpredictable consequences. The Async pipe unwraps the value of the promise as it is returned and then renders it out. This only happens when the value of available.

  • DatePipe - is used to format dates. It takes the valid javascript date objects as inputs and formats the data according to the specified options.
    TS Code
    today: new Date();
    HTML Code
    {{ today | date }}
    
    
  • CurrencyPipe - formats numbers as currencies and places the currency symbol as well.
    TS Code
    amount: number = 5000;
    HTML Code
    {{ amount | currency: 'INR'}}

  • AsyncPipe - is used to unwrap promises and observables and renders the results as and when it is available..

    TS Code
    count: Observable<number>;
constructor() {
this.countdown();
}
countdown() {
     let i = 100;
     this.count = new Observable((observer) => {
   let id;
       id = setInterval(() => {
         if(i > 0) {
           i = i-1;
           observer.next(i);
         } else {
           clearInterval(id);
           observer.complete();
         }
       }, 50);
    })
}


HTML Code

{{ count | async }}

  • DecimalPipe - is used to format numbers with decimal digits. It lets us specify the minimum and maximum number of digits after the decimal.

    TS Code
amount: number = 5000;

HTML Code

{{ amount | decimal: '0.0-2'}}

  • TitleCasePipe - is used to change the case of the text to titlecase.

    TS Code
name: string = 'ZEOLEARN';

HTML Code

{{ name | titlecase}}

  • JsonPipe - is used to render out json data on the page.

    TS Code
person: any = {
name: 'Zeolearn',
id: 12
}

HTML Code

{{ person | json }}

  • SlicePipe - is used with ngFor to slice the array and only render out the remaining elements from the array.

    TS Code
people: string[] = ["A", "B", "C", "D"];

HTML Code

<div *ngFor="let char of people | slice:1">
   {{char}}
</div>
  • PercentPipe - is used to display decimals numbers as percentages.

    TS Code
a: number = 0.259;

HTML Code

A: {{ a | percent}}

  • UpperCasePipe - is used to display strings in all uppercase alphabets.

    TS Code
name: string = "ZEOLEARN";

HTML Code

{{ name | uppercase}}

  • LowerCasePipe - is used to display strings in all lowercase alphabets.

    TS Code
name: string = "ZEOLEARN";

HTML Code

{{ name | lowercase}}

An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser.

The Angular Ahead-of-Time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the +browser.

Faster rendering - With AOT, since the application code is already compiled, the browser downloads a pre-compiled version of the application and therefore can load the app immediately without having to recompile the whole app.

Fewer asynchronous requests - The inlining of the external HTML templates and CSS style sheets eliminate separate ajax requests for those source files.

Smaller Angular framework download size - Since the application code is already compiled, there's no need to download the Angular compiler along with the code. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.

Detect template errors earlier - The AOT compiler detects and reports template binding errors during the build step before users can see them. Thus it saves a lot of error finding and debugging time.

Better security - AOT compiled HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.

ng build --prod

The CLI uses a bunch of tools together to compile the code files including the HTML, CSS and TS files from individual files into a single bunch which is references in the index.html file as main.js. Most of the work is done during the build time and there is almost nothing left to do at the runtime. The CLI uses a tool called WebPack to achieve the final build that can be deployed.

Beginner

AngularJS was the initial version of the Angular framework released in October 2010 mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications. The revolutionary framework, with its two-way binding concepts, took the JavaScript community by storm and developers adopted the framework quickly. AngularJS used JavaScript as the primary programming language.

After a few years, Angular 2, which was a complete rewrite of the whole framework, was released. It adopted TypeScript as the primary programming language.

Since then, until today, more than 4 major versions of Angular have come out, improving the framework and making it better than before. Angular is the blanket term used to refer to Angular 2, Angular 4 and all other versions that come after AngularJS. Angular 2, 4, 5, 6 and now 7 are all open-source, TypeScript-based front-end web application platforms.

Event binding in Angular is used to respond to some DOM events. For example, actions on click of buttons require event binding. In this very specific example, the click event is required to be bound to a method in the code so whenever the user clicks on the button, the click event is fired which in turn executes the bound method. This is called event binding.

There are many different events exposed by the HTML and JS APIs that developers can use to perform actions. Here is an example of event binding.

<button class="btn btn-success" 
(click)="registerUser()">Register</button>

The above is the simplest example of event binding in Angular. The method registerUser() will be executed every time the user clicks on the button.

Property binding in Angular is used to bind HTML properties to variables and objects. For example, the image url (the src property) of the <img> HTML element can be bound to a string property. This allows us to bind values to properties of an element to modify their behavior or appearance.

The syntax for property bindings is to put the property onto the element wrapped in brackets [property]. The name should match the property, usually in a camel case like src. Here is an example of the TS and HTML code.

TS Code

imageUrl: string = "https://via.placeholder.com/150"/>

HTML Code

<img [src]="imageUrl" height="150" width="150"/>

In the above code, the imageUrl is a TS property (of type String) that holds the URL to an image resources. Since the src property of the image HTML element is bound to the imageUrl property using the property binding syntax, the value of the imageUrl property will be evaluated first and then assigned to the src property.

If you change the value of the imageUrl property, the image element will reflect the changes in real time.

Two-way data binding was one of the most prominent selling points of Angular that made developers go WOW! Basically, two-way binding means that the changes made to the DOM (due to some events or user interactions) are reflected back in the model or application data and the changes in the data or model are reflected in the application’s view immediately. This saves developers a lot of trouble that they had to go through to keep both in sync.

Let’s have a look at an example.

TS Code.

username: string;

HTML Code

<input [(ngModel)]="username">
<p>Hello {{username}}!</p>

If you run the above code within an Angular component, you will simply get to see a text input and a paragraph text. Try changing the text in the input field. Did you see that? The text in the paragraph changes automatically, does not it?

How does that happen? Well, that’s because of two-way binding. Let’s have a look at what is happening here, step-by-step.

The ngModel directive here ensures that the username property in the class (the TS code above) is always updated when you or the user updates the input field’s value. It also ensures that if the value of the property happens to change over time because of some code executions, the changes will immediately propagate to the view and the user will see the value change in the page. 

In the above demo, the value of text in the paragraph changes because it is bound to the value of the username property which is in turn bound to the value of the input field. It all works together.

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.

Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name.

There are two primary structural directives in Angular - ngFor and ngIf.

NgIf is very useful if you want to show or hide parts of your application based on a condition. For example, if you want to show or hide an element on the page based on the value of a variable, you can do that using ngIf. Let’s have a look at the code.

TS Code

import { Component } from '@angular/core';
 
@Component({
   selector: 'app-example',
templateUrl: './example.component.html',
   styleUrls: ['./example.component.css']
})
export class ExampleComponent {
    show: boolean = true;
}

HTML Code

<p>Show this all the time</p>
<p *ngIf="show">
   Show this only if "show" is true
</p>

When you test the above component, you will only the second p tag in the page when the value of the boolean property “show” is true. Please note that the p element is not only hidden, but is completely removed from the DOM. The great advantage of this is, that this method is not interfering with any CSS-Style-sheets at all. It is simply removing anything.

NgFor is the other structural directive which is used to render elements or components on the page based on the contents of an iterable or simple an array. Let’s look at an example.

Consider the following array of JSON data inside a component class.

policies: [] = [
      {id: 0, name: "policy001"},
     {id: 2, name: "policy002"},
     {id: 3, name: "policy003"},
     {id: 4, name: "policy004"},
     {id: 5, name: "policy005"}, 
];

To render the data from the array, we can use ngFor as shown in the HTML template code below.

<table>
<thead>
<th># Policy ID</th>
<th>Policy name</th>
</thead>
<tbody>
<tr *ngFor="let policy of policies">
<td>{{policy.id}}</td>
<td>{{policy.name}}</td>
</tr>
</tbody>
</table>

For each element in the array - policies, the HTML <tr> is rendered in the page. We can use the temporary object “policy” to access the data inside the object (one at a time) during the iteration. If you are coming from a C# background, you can think of ngFor like a for-each loop.

Note: The let and of keywords are mandatory in the ngFor expression.

Description

AngularJS developers have massive opportunities in the present market. In the current market scenario, there are huge opportunities available for web developers in general. Most of the MNCs are looking to hire AngularJS developers for their projects. Hence, you should prepare yourself well in advance.

 

To support you in this journey, we’ve brought you a list of most frequently asked AngularJS interview questions along with the answers which your interviewer expects at the time of interview. Angularjs Interview Questions have been designed specially to get you familiarized with the nature of the questions. The Angularjs interview questions and answers here start with some basic concepts and are continued to the advanced level. These are the most frequently asked interview questions on Angularjs that will help you to ace the toughest interviews that come your way.

 

We hope these Angular interview questions and answers helped you to understand the basic and advanced level of AngularJS. If you are a beginner looking to make it big in the web development market, the basic interview questions on Angular JS will enable you to crack your upcoming interviews easily. Keep visiting these AngularJS interview questions with ready answers to have a complete command over Angular JS.

Help the employer recognize the value you’ll bring to their organization. Start preparing with these mock Angular JS interview questions and answers today!

Read More
Levels