Angular Interview Questions: Beginner level – The Screening Round
50 Essential Beginner Angular JS Interview Questions & Answers frequently asked by top MNCs.Angular JS interview question, Angular component, TypeScript, Data Binding, Form Control, Routing, HTTP Client
Angular JS interview question, Angular component, TypeScript, Data Binding, Form Control, Routing, HTTP Client
Angular is a development platform and framework built on TypeScript, created and maintained by Google. It is used to build scalable Single-Page Applications (SPAs) and provides a component-based architecture alongside robust tools for routing, state management, and client-server communication.
AngularJS (Angular 1.x) is based on JavaScript and uses an MVC (Model-View-Controller) architecture. Angular (Angular 2+) is a complete rewrite based on TypeScript and uses a Component-based architecture. Modern Angular is faster, highly modular, and provides better support for mobile browsers and object-oriented programming.
TypeScript is a strict syntactical superset of JavaScript that adds optional static typing. Angular uses it because it enables powerful tooling (like robust IDE auto-completion), better refactoring capabilities, and early detection of errors during compile time rather than runtime, making enterprise codebases much easier to maintain.
The core building blocks are:
- Components: Control a patch of the screen called a view.
- Templates: The HTML defining the component’s view.
- Modules (NgModules): Containers for cohesive blocks of code.
- Services: Classes that handle business logic or data fetching.
- Dependency Injection (DI): Mechanism to inject services into components.
A component controls a portion of the screen (a view). It consists of a TypeScript class containing the logic, paired with an HTML template and CSS styles. Components are defined using the @Component decorator.
import { Component } from '@angular/core';
@Component({
selector: 'app-hello',
template: '<h1>Hello {{name}}</h1>'
})
export class HelloComponent {
name = 'Angular';
}Data binding is the process that connects application data (TypeScript class) with the user interface (HTML template). It ensures that changes in the data are reflected in the UI, and user interactions in the UI update the data without requiring manual DOM manipulation.
Angular supports four types of data binding:
- Interpolation:
{{ value }}(Component to DOM) - Property Binding:
[property]="value"(Component to DOM) - Event Binding:
(event)="handler()"(DOM to Component) - Two-Way Binding:
[(ngModel)]="value"(Bi-directional synchronization)
Interpolation is a form of one-way data binding used to embed dynamic string values directly into HTML text nodes or attributes using double curly braces {{ }}.
<!-- Component: title = 'Dashboard' -->
<h1>Welcome to the {{ title }}</h1>Interpolation {{ }} converts the evaluated expression to a string and is generally used for rendering text. Property Binding [ ] sets an element property directly and is required when binding non-string data types (like booleans, objects, or arrays) to DOM properties (e.g., [disabled]="isDisabled").
Event binding allows you to listen to DOM events (like clicks, keystrokes, or mouse movements) and execute a method in the component. It uses parentheses ( ) around the event name.
<button (click)="submitData()">Submit</button>Two-way data binding synchronizes data between the model (component) and the view (UI) in both directions simultaneously. In Angular, this is achieved using the “banana-in-a-box” syntax [(ngModel)]. When the user types in an input, the property updates; when the property changes in code, the input reflects it.
ngModel for two-way binding?To use [(ngModel)], you must import the FormsModule from @angular/forms into your application’s module (or standalone component’s imports array).
Directives are classes that add additional behavior to elements in your Angular applications. They allow you to manipulate the DOM, change the appearance of elements, or create reusable custom behaviors.
The three kinds of directives are:
- Components: Directives with a template (the most common).
- Structural Directives: Change the DOM layout by adding or removing DOM elements (e.g.,
*ngIf,*ngFor). - Attribute Directives: Change the appearance or behavior of an element, component, or another directive (e.g.,
ngClass,ngStyle).
*ngIf with an example.*ngIf is a structural directive that conditionally adds or completely removes an element from the DOM based on whether the expression is truthy or falsy.
<div *ngIf="isLoggedIn">
Welcome back, User!
</div>*ngFor with an example.*ngFor is a structural directive used to loop over an iterable (like an array) and render a template for each item.
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>*ngIf and the hidden attribute?*ngIf physically removes the element from the DOM entirely when the condition is false, which saves memory and prevents Angular from checking bindings inside it. The [hidden] attribute keeps the element in the DOM but uses CSS (display: none) to hide it, which can be useful if rendering the element is computationally expensive and toggled frequently.
ngClass?ngClass is an attribute directive that allows you to dynamically add or remove CSS classes on an HTML element based on a boolean expression or state in the component.
<button [ngClass]="{'btn-active': isActive, 'btn-disabled': !isActive}">
Click Me
</button>A Service is a TypeScript class that contains highly cohesive business logic, data fetching mechanisms, or state meant to be shared across multiple components. Services keep components lean, focusing only on the view layer.
Dependency Injection is a core design pattern in Angular where the framework creates and delivers required objects (dependencies like Services) to a class (like a Component) automatically through its constructor, rather than the class instantiating the object itself using the new keyword.
@Injectable() decorator do?The @Injectable() decorator marks a class as participating in the dependency injection system. It tells Angular that this class can be injected as a dependency into other components or services, and that it may also require dependencies to be injected into its own constructor.
providedIn: 'root' mean in a service?When configuring an @Injectable({ providedIn: 'root' }), it registers the service as a singleton at the application root level. This means there is only one instance of the service shared across the entire application, and Angular can tree-shake (remove) the service from the final bundle if it is never actually injected anywhere.
Pipes are simple functions used in HTML templates to transform data for display without altering the original property in the component. They use the pipe character |.
<p>The date is {{ today | date:'shortDate' }}</p>Common built-in pipes include:
DatePipe(formats dates)UpperCasePipe/LowerCasePipe(changes text case)CurrencyPipe(formats numbers as currency)JsonPipe(converts an object to a JSON string for debugging)AsyncPipe(resolves Promises/Observables automatically)
A Pure Pipe executes only when Angular detects a pure change to the input value (like a primitive value change, or a completely new object reference). An Impure Pipe executes on every single component change detection cycle (e.g., every keystroke or mouse move), which can severely impact performance. Pipes are pure by default.
Lifecycle hooks are special methods that allow developers to tap into specific moments in a component’s or directive’s lifecycle. Angular calls these methods when creating, updating, or destroying instances (e.g., ngOnInit, ngOnChanges, ngOnDestroy).
ngOnInit and when is it called?ngOnInit is a lifecycle hook that is called exactly once, immediately after Angular has initialized all data-bound properties (like @Input). It is the standard place to put initialization logic, such as calling a service to fetch data.
ngOnInit instead of the constructor?The constructor is a standard TypeScript feature used primarily for dependency injection. When the constructor runs, Angular has not yet evaluated the component’s @Input() bindings. ngOnInit guarantees that all inputs have been fully resolved, making it the safe place for component initialization logic.
ngOnDestroy used for?ngOnDestroy is called immediately before Angular physically removes the component from the DOM. It is crucial for cleanup tasks, such as unsubscribing from RxJS Observables, detaching event handlers, or clearing intervals to prevent severe memory leaks.
A parent component passes data to a child component using the @Input() decorator on the child’s property, and binding to it via property binding in the parent’s template.
// Child Component
@Input() item: string;
<!-- Parent Template -->
<app-child [item]="parentData"></app-child>A child component sends data back to the parent by emitting custom events using the @Output() decorator combined with an EventEmitter. The parent listens to this event via standard event binding.
// Child Component
@Output() itemSaved = new EventEmitter<string>();
save() { this.itemSaved.emit('Success!'); }
<!-- Parent Template -->
<app-child (itemSaved)="handleSave($event)"></app-child>Angular Routing is a mechanism that allows users to navigate between different views (components) in a Single Page Application (SPA) by updating the browser’s URL without reloading the entire page.
<router-outlet>?The <router-outlet> is a directive from the router library. It acts as a placeholder or dynamic placeholder in your template where the Router physically inserts the component matched by the current active URL route.
routerLink and why is it used instead of href?routerLink is an Angular directive used on anchor tags for navigation. Using a standard HTML href causes the browser to completely reload the page, losing all application state. routerLink intercepts the click, prevents the full reload, and uses the Angular router to load the component seamlessly.
Template-Driven Forms rely heavily on HTML directives (like ngModel, required, minlength) to build the form model and logic directly within the HTML template. They are simple, highly declarative, and suitable for basic forms.
Reactive Forms take a model-driven approach. You define the form’s structure, validation, and logic strictly in the TypeScript component class using FormGroup and FormControl objects. They are robust, highly scalable, and easier to unit test, making them preferred for complex enterprise forms.
FormControl?A FormControl is the fundamental building block of Reactive Forms. It tracks the value and validation status of a single individual form input element (like an email text box or a checkbox).
HttpClient in Angular?HttpClient is an injectable service provided by Angular that performs HTTP requests to external APIs and web servers. It executes asynchronous operations and always returns data wrapped in an RxJS Observable.
An Observable is a feature of the RxJS library representing a continuous stream of data over time. Unlike Promises that resolve only once, an Observable can emit multiple values sequentially and can be cancelled (unsubscribed) at any time.
HttpClient request do nothing until you call .subscribe()?Observables returned by Angular’s HttpClient are “Cold”. This means the execution of the HTTP request is deferred and will not fire until a component or service explicitly subscribes to it using the .subscribe() method.
A Promise emits a single value (or failure), executes immediately upon creation, and cannot be cancelled. An Observable can emit multiple values over time, is lazy (only executes when subscribed to), and can be easily cancelled or retried using RxJS operators.
The async pipe subscribes to an Observable (or Promise) directly in the HTML template and unwraps the emitted value for display. Crucially, it automatically unsubscribes when the component is destroyed, preventing memory leaks.
<ul>
<li *ngFor="let user of users$ | async">{{ user.name }}</li>
</ul>A Route Guard is an interface that tells the Angular router whether it should allow or deny navigation to a requested route. It is primarily used to implement authentication (e.g., preventing an unauthenticated user from accessing a secured dashboard component).
Lazy Loading is a performance optimization technique where feature modules or components are loaded asynchronously on-demand only when the user navigates to their specific route. This dramatically reduces the initial bundle size and speeds up the application’s initial loading time.
The Angular Command Line Interface (CLI) is a powerful terminal tool that allows developers to initialize, develop, scaffold (generate components/services), test, and build Angular applications quickly without writing boilerplate code manually.
Common commands include:
ng new app-name(creates a new app)ng serve(starts a local dev server)ng generate component childorng g c child(scaffolds a component)ng build(compiles the app for production)
angular.json file?The angular.json file is the central workspace configuration file for the Angular CLI. It dictates how the project is built and served, manages environments, and specifies arrays for global CSS stylesheets and external third-party JavaScript scripts to inject.
Content Projection allows a developer to pass HTML content from a parent component into a specified placeholder inside a child component’s template. This is achieved using the <ng-content> tag, creating highly reusable wrapper components (like custom modals or cards).
Introduced in recent versions of Angular, Standalone Components allow developers to build components without declaring them in an NgModule. You set standalone: true in the decorator, and the component manages its own dependencies via an imports array, drastically simplifying architecture.
The environment.ts files define environment-specific variables (like API endpoints or feature toggles) for your application. Angular CLI automatically replaces the default environment.ts with environment.prod.ts when you perform a production build using ng build --configuration production.