Angular Interview Questions (0-2 Years Experience)


Top 10 Angular Interview Questions for Freshers & 0-2 Years Experience | Angular Interview Prep


1. What's the main difference between Angular and AngularJS?



Angular Interview Questions (0-2 Years Experience)
Angular Interview Questions (0-2 Years Experience)



You know, this question about Angular's history comes up a lot. Here's the short, interesting story: Google first released AngularJS back in 2010. But then, they realized it had some shortcomings, so they decided to completely rewrite the whole framework and just called it Angular. They dropped "JS" because now the new version can use TypeScript too.

So, for the main differences:

  • Language: AngularJS only supported JavaScript. Angular, though, supports both JavaScript and TypeScript. A big perk of TypeScript? You can actually see errors at compile time, which JavaScript doesn't do. Plus, TypeScript supports cool stuff like classes and interfaces, which is great for programming.

  • Architecture: AngularJS had a Model-View-Controller (MVC) architecture. Angular, on the other hand, uses a component-based architecture, and believe me, that's way faster than MVC.

  • CLI Tool: AngularJS didn't have a CLI tool. But Angular? It has a CLI tool that makes creating components, services, and other things super easy.

  • Dependency Injection: AngularJS didn't use dependency injection. Angular, however, does use dependency injection, which is a really good design pattern. We'll talk more about that later.

  • Mobile Support: AngularJS didn't support mobile browsers, but Angular does support mobile browsers.

  • Speed: AngularJS wasn't super fast, which was one of the reasons Google replaced it. Angular is much, much faster thanks to its data binding techniques and that component-based architecture.

Think of Angular as a big upgrade over AngularJS! 

---------------------------

2. What is TypeScript, and what are its advantages over JavaScript?

After this, you'll be able to tell any interviewer exactly why we need TypeScript!

Think of it like this: TypeScript has things like a type system, enums, generics, interfaces, and lots more that JavaScript just doesn't have. But here's the catch: browsers don't understand TypeScript code directly. So, what Angular does is it first compiles (or converts) all that TypeScript code into JavaScript, and then it runs it in the browser.

Now, for the key points about TypeScript:

  • Typing: TypeScript is a strongly typed language, while JavaScript is a loosely typed language. For example, in TypeScript, if you declare a variable as a string and then accidentally try to assign an integer to it, TypeScript will show you a compile-time error. That's awesome because it catches mistakes early. In JavaScript, you wouldn't see that error until runtime, which could break your application!

  • Superset: TypeScript is a superset of JavaScript. What does that mean? It means any valid JavaScript code is also valid TypeScript code. But on top of that, TypeScript adds extra features like classes and interfaces.

  • Object-Oriented Features: TypeScript boasts object-oriented features like classes, inheritance, encapsulation, and more. This is really, really good for building software. JavaScript, plain and simple, doesn't have these.

  • Error Detection: This is a big one: TypeScript detects errors at compile time. JavaScript, as we mentioned, only detects them at runtime. That's a huge advantage for TypeScript.


3. What are Components in Angular? What files typically make up a component?

Alright, let's talk about components. This is super fundamental in Angular.

The simplest definition is: Components are the most basic UI building blocks of an Angular application.

Imagine a website, like interviewhappy.com. On that single page, you could have many different components: maybe a menu component with all your navigation items, a login component where users enter their username and password, or a product list component showing all the items. The idea is that the page itself stays the same, but based on what's happening, different components get updated, replaced, or refreshed.

In your code, an Angular component is usually made up of four files that work together:

  • .css file: This is where all the CSS code for your component's styling goes.

  • .html file: This is your HTML template, defining the look and feel of your component.

  • .spec.ts file: This file is specifically for writing unit tests for your component.

  • .component.ts file: This is the most crucial one. It's the TypeScript file that links all the other component files (CSS, HTML) together. It also defines the component's metadata, like its selector, templateUrl, and styleUrls.

When you first create a new Angular project, Angular will even generate that initial default component for you.


4. What is selector and template in Angular?

This is a pretty straightforward one, but important to cover.

  • Selector: A selector is basically a unique name that helps Angular identify each component within your application's component tree. For instance, if you have hundreds of components, the selector makes it easy to pinpoint each one. When your main index.html page loads, an app-root tag (which is a common selector) will actually be replaced by the HTML of your app-root component.

  • Template: The template is simply the HTML view of an Angular component. You usually define it using the templateUrl attribute, pointing to your component's HTML file (like app.component.html). You can also write the HTML directly inline using the template attribute if it's a small piece of code.

So, in a nutshell, a template is the HTML representation of your Angular component.


5. What is a Module in Angular? What is the app.module.ts file?

Let's break down what a module is in Angular.

The simplest definition is: A module is a place where you can group related components, directives, pipes, and services that belong to your application. It helps organize your code.

Now, let's look at app.module.ts. When you create an Angular project, this file is automatically generated, and it's considered your root module, often called the AppModule.

Inside this app.module.ts file, you'll see the @NgModule decorator, and within it, some important sections:

  • declarations: This is where you declare all the components, directives, and pipes that are part of this module. A single module can have many components. AppComponent is usually the default component for the root module.

  • imports: With imports, you can bring in functionalities from other Angular modules into your app.module. For example, BrowserModule is always there by default because it provides essential services to run your application in a browser. So, modules can import other modules and use their services.

  • providers: This is where you register services for dependency injection. (We'll get into this a bit more later, it's a slightly complex topic).

  • bootstrap: This tells Angular which component to start up first when the application loads. If you have multiple components declared, you can choose which one to bootstrap here.

So, a module is essentially a logical container. For smaller apps, your root AppModule might be all you need. But for larger, complex applications, you'll likely create more modules, potentially different types of modules.


6. How does an Angular app load and start? What are index.html, app-root selector, and main.ts file?

This is a great question about how everything kicks off in an Angular app.

Here's the sequence to remember:

  1. When a client sends a request, it first hits the index.html page. Since Angular builds single-page applications, index.html is that single page.

  2. Then, index.html invokes the main.js file. This main.js is actually the JavaScript version of your main.ts file.

  3. The main.ts file is the entry point of your web app. It's responsible for compiling the app and bootstrapping the app module so it can run in the browser.

  4. After that, the app module will then bootstrap the app component (which is also known as the app-root component).

  5. Finally, the HTML of the app component is what you'll actually see in your browser.

Let's quickly prove this with the code:

  • If you look at your index.html, you'll spot an <app-root> tag. This isn't standard HTML; it's an Angular component.

  • When index.html loads, the Angular CLI loads some JavaScript files, including main.js.

  • The main.js (which came from main.ts) runs. In main.ts, you'll see bootstrapModule, which is currently bootstrapping your AppModule.

  • Inside your AppModule (in app.module.ts), the bootstrap array points to AppComponent.

  • And finally, if you check app.component.ts, you'll see its selector is defined as app-root. This is why that <app-root> tag in index.html gets replaced by the HTML content from app.component.html.

So, the whole story is: Browser loads index.html -> main.ts starts -> main.ts bootstraps AppModule -> AppModule bootstraps AppComponent -> and you see the AppComponent's HTML in the browser.


7. What is Data Binding in Angular? What are its main types?

This is a really important concept!

At its core, data binding is how your component's TypeScript code communicates with its HTML view. In an Angular project, you write all your business logic (like fetching data from APIs) in your app.component.ts file. But then, you need to display that data in your HTML file, which is also called the "view." Data binding is the technique that makes this data transfer happen.

There are essentially three ways data can flow:

  • From Component to HTML template (Output Data):

    • String Interpolation ({{ }}): This is for displaying property values from your TypeScript code directly in the HTML.

    • Property Binding ([property]="value"): This lets you bind a property from your TypeScript to an HTML element's property.

  • From View to Component (Input Data):

    • Event Binding ((event)="handler()"): This is how you listen for events in your HTML (like a button click) and trigger methods in your component's TypeScript.

  • Data traveling both ways:

    • Two-Way Data Binding ([(ngModel)]="value"): This is when data can flow in both directions – if something changes in the view, it updates the component, and if the component changes, it updates the view.

The first three are one-way data binding techniques, and the last one is a two-way data binding technique. (Just a quick note: HTML template and view are basically the same thing, and sometimes people just say "component" when they mean the TypeScript code file for simplicity.)


8. What are Directives? What are the types of directives?

Let's talk about directives!

The simplest way to put it is: Directives are classes that add additional behavior to elements in your Angular applications. For example, you can use a directive to change the color of a button.

There are three main types of built-in directives that Angular provides:

  • Structural Directives: These actually change the appearance of the DOM by adding or removing elements from it.

    • Examples: *ngIf, *ngFor, *ngSwitch. Think about adding a new item to a list on a webpage – a structural directive like *ngFor would handle that.

  • Attribute Directives: These change the appearance or behavior of an element (or even another component or directive). They don't mess with the DOM's structure, just its attributes or styles.

    • Examples: ngClass, ngStyle. That button color change example? That's typically done with an attribute directive.

  • Component Directives: This is interesting – component directives are just directives that have their own templates. So, essentially, all components are a type of directive! This type is super common because components are what you use to display the first view of your application.


9. What's the difference between Component, Attribute, and Structural Directives?

Interviewers love questions about differences, so let's quickly recap the directives!

  • Component Directive: This one is responsible for showing the first view of your component. It's the most used because it's tied to an HTML template. If you were to remove it, your component's initial view wouldn't even be displayed.

  • Structural Directive: This is responsible for adding and deleting HTML elements within the view that the component directive displays. It manipulates the actual structure of the DOM.

  • Attribute Directive: This is responsible for changing the appearance of your view by adding or removing CSS classes or styles from HTML elements. It modifies existing elements.

And how you represent them:

  • Component Directive: Starts with an @ sign, like @Component.

  • Structural Directive: Starts with an asterisk * sign, like *ngIf or *ngFor.

  • Attribute Directive: Is set inside square brackets, like [ngClass] or [ngStyle].


10. What is a Decorator?

This is a really important question!

The simplest definition you can give any interviewer is: Angular decorators store metadata about a class, method, or property.

Now, what's metadata? It's simply data that provides information about other data. Think of a book: the author's name, title, price, publisher – all that info about the book is metadata. It's not the main story, but it gives you information about it.

Similarly, in an Angular component file, your main logic is inside the AppComponent class. But information like its selector, templateUrl, and styleUrls? That's all metadata. The decorator is what stores all this metadata for the component.

The same goes for a module: the @NgModule decorator stores all its metadata, like declarations, imports, providers, and bootstrap.

One key thing to remember about Angular decorators: they all start with an @ symbol.


11. What are the types of Decorators?

Let's quickly go through the types of decorators. We have four main categories:

  1. Class Decorators: Within this category, the actual decorators you'll use are @NgModule and @Component. These are the most important ones to remember.

  2. Property Decorators

  3. Method Decorators

  4. Parameter Decorators

(The others are a bit more complex and less commonly asked about in basic interviews, so focus on @NgModule and @Component.) The main thing you'll notice about all decorators is they all begin with an @ symbol.


12. What are Life Cycle Hooks in Angular?

This question is super important and comes up in many interviews!

Basically, in simple English: A component, from its creation all the way to its destruction, goes through several stages. These stages are what we call life cycle hooks. These stages cover activities like when the component is first instantiated, when its HTML view is rendered, when any child components are created, and finally, when the component is destroyed.

Why do developers need these hooks? Well, sometimes we want to add specific behavior to a component at certain points. For instance, maybe you want to run some code right when the component is first created. That's why you need these specific component hooks where you can place your code.

Here's an overview of some important ones:

  • constructor: This is the default method of a TypeScript class. It runs when the class is instantiated, and it always runs before any Angular hook. It's not technically part of the life cycle hooks, but it's very important to know.

  • ngOnChanges: This one is called when an input property of the component changes. Remember the @Input() decorator? This hook is related to that.

  • ngOnInit: This is probably the most important hook. It's called once after the constructor and ngOnChanges (for the first time). You typically use it for your initial setup logic.

  • ngDoCheck: This isn't as critical, but its purpose is to help handle changes that Angular might not otherwise detect.

  • ngOnDestroy: This is called just before the component is destroyed. It's where you'd put any cleanup code, like unsubscribing from observables.


13. What is RxJS, and what are Observables in Angular? How are they different from Promises?

Before we talk about observables, let's quickly clarify their relationship with RxJS.

  • What is RxJS? Think of RxJS as the "father" of Observables. From the RxJS website, it's described as "a library for composing asynchronous and event-based programs by using observable sequences." In simpler terms, it's a JavaScript library that lets us work with asynchronous data streams using observables. "Event-based programs" means when you send a request, you get immediate and continuous responses from the server, like streaming data.

  • Why do Angular developers need RxJS? Because Observables are introduced by the RxJS library, not Angular itself. There's a common misconception that Observables are part of Angular, but they're not. We use RxJS in Angular to work with Observables. Plain JavaScript or other frameworks can use them too.

RxJS has two main players:

  • The Observable: This is what streams the data (or "sends the data in chunks"). It can emit multiple values over a period of time.

  • The Observer (or Subscriber): This is what receives (or "subscribes to") the data sent by the Observable.

How to implement an Observable (it's a simple three-step process!):

  1. Import Observable from the rxjs library.

  2. Create the Observable and define what data it will emit.

  3. Subscribe to the data in your component.

Now, for the big difference from Promises:

  • Observables are lazy: This is a crucial point. An Observable will not even generate or emit data unless there is at least one subscriber! If you create an Observable but don't subscribe to it, nothing happens. This is the beauty of it because it prevents wasting resources (like memory) if no one is actually consuming the data.

  • Promises are eager: A Promise doesn't need a subscription to start. It will generate and try to send its data regardless of whether there's a listener.

So, Observables are smart – they only work when they're needed.


14. What is Authentication and Authorization in Angular?

These two concepts are super common in almost every web technology, not just Angular.

  • Authentication: This is the process of verifying the user's identity. 99% of the time, this means validating the username and password the user provides. It answers the question: "Are you who you say you are?"

  • Authorization: This happens after successful authentication. It's the process of determining what a user is allowed to do or access based on their role. It answers the question: "What are you allowed to do/see?"

The key thing to remember is that authentication always comes before authorization. You have to prove who you are before the system decides what you can do.


15. Explain the Token Authentication Process (like JWT) in an Angular application.

This is a very common way to handle authentication in modern web apps, like Angular ones. Here's how it generally works with a JWT (JSON Web Token):

  1. The user sends their username and password to your backend API.

  2. The API authenticates those credentials. If they're valid, the API creates a JWT and sends it back to the client.

  3. Your Angular application on the client side receives this JWT and typically stores it (often in localStorage).

  4. For all subsequent requests that need authentication (like fetching user-specific data), your Angular app includes this stored JWT in the header of every request it sends to the API.

  5. The API then receives the request, validates the token. If the token is valid (not tampered with, not expired), the API processes the request and sends the requested data back to the client.

The cool part about this is the user only has to enter their credentials once per session!

Post a Comment

0 Comments