Angular Interview Question | Top Interview Question | angular

Angular Interview Question
-
AngularJs Angular JavaScript-based Framework TypeScript based Framework It follows a Model-View-Controller (MVC) architectural pattern. It follows a component-based architecture with a hierarchical dependency injection system. AngularJS can suffer from performance issues when handling large-scale applications due to its two-way data binding and digest cycle. Angular provides improved performance and speed compared to AngularJS. It introduced a change detection mechanism that is faster and more efficient. -
Eager Loading is the default loading in Angular. It loads all the modules and their components when the application starts. This means that all the components are available to the user immediately. Eager loading is a good choice for small to medium-sized applications, where the number of components and modules is limited.
Lazy Loading is a technique where modules are only loaded when they are needed. Lazy loading is a good choice for large applications -
Decorators are feature of TypeScript and are implement as a functions. The name of decorator start with @symbol following by brackets and arguments.
Decorators are simply a functions that return functions. These function supply metadata to angular about a particular class, property , value or method
Decorators are invoked at runtimeIn AngularJS, decorators are functions that allow a service, directive, or filter to be modified before it is used.
There are four main types of angular decorators:
- Class decorators , such as @Component and @NgModule
- Property decorators for properties inside classes, such as @Input and @Output
- Method decorators for methods inside classes, such as @HostListener
- Parameter decorators for parameters inside class constructors, such as @Inject
Category Decorator Description Class Decorators @Component, @Directive, @Pipe, @NgModule, @Injectable Defines classes like components, services, modules, etc. Property Decorators @Input, @Output, @HostBinding Binds properties to parent-child data flow or DOM properties. Method Decorators @HostListener Binds methods to events on DOM elements. Parameter Decorators @Inject, @Optional,@Self(), @SkipSelf(), @Host() Used for dependency injection in constructors. -
@HostBinding() decorator allows you to set the properties of the host element from the directive class. With the help @HostBinding() decorator we set height, width, color, margin, border, etc., or any other internal properties of the host element in the directive class.
<button appHighlight>Hover Me</button>
import { Directive, HostBinding, HostListener } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { // HostBinding binds the style of the host element @HostBinding('style.backgroundColor') backgroundColor: string = ''; @HostListener('mouseenter') onMouseEnter() { this.backgroundColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.backgroundColor = ''; } } -
The @HostListener decorator in Angular provides a convenient way to listen for events on the host element of a component. It allows to define event handlers directly within the component class. In order to listen to events on the host element of the directive or component, one uses Angular’s @HostListener decorator. This decorator function takes an event name as a parameter. The related function is called by the host element when that event is fired.
-
A FormArray is a part of Angular's reactive forms module. It is a way to manage an array of form controls, where each form control can represent a field, a group of fields, or another array of fields. This is especially useful when you need to handle dynamic or variable numbers of form fields, like when adding or removing fields at runtime.
FormArray allows you to build forms that have a variable number of elements, such as a list of addresses, emails, phone numbers, or tasks.
Key Points about FormArray:- Dynamic Management: You can dynamically add or remove controls to/from the FormArray.
- Index-based Access: Each control inside a FormArray can be accessed by its index.
- Validators: Similar to FormControl and FormGroup, you can apply validators to FormArray elements
- Structure: A FormArray can contain multiple FormControls, FormGroups, or other FormArrays.
-
In my project, I primarily used several Angular core modules:
- FormsModule and ReactiveFormsModule: For handling forms, validations, and building reactive forms.
- HttpClientModule: To handle API calls and interact with backend services.
- RouterModule: For defining and managing routes between different components and pages.
- Angular Material: I also used Angular Material components for UI elements, such as dialogs, tables, and forms.
-
Angular calls lifecycle hook methods on directives and components as it creates, changes, and destroys them.
Lifecycle event sequence
- ngOnChanges()
- ngOnit()
- ngDoCheck()
- ngAfterContentInit()
- ngAfterContentChecked()
- ngAfterViewInit()
- ngAfterViewChecked()
- ngOnDestroy()
A directive has the same set of lifecycle hooks, minus the hooks that are specific to component content and views.
-
Pipes in Angular are a way to transform data within templates. They take in data as input, transform it, and return the modified output. This is particularly useful for formatting data (e.g., dates, currency) directly in the template without modifying the underlying component logic.
Ex:
{{ user.name | uppercase }}
{{ user.joinedDate | date:'fullDate' }}
Key Difference:
Feature Pure Pipes Impure Pipes Execution Executed only when input reference changes. Executed on every change detection cycle. Performance More efficient; fewer executions. Less efficient; frequent executions. Use Case Use for static or reference-based changes. Use for dynamic, frequently changing data. Example of Pure Pipe:
predefined : date, uppercase, and currency pipes are pure pipes
@Pipe({ name: 'purePipeExample', pure: true }) export class PurePipeExample implements PipeTransform { transform(value: number): number { return value * 2; } }
Example of Impure Pipe
@Pipe({ name: 'impurePipeExample', pure: false }) export class ImpurePipeExample implements PipeTransform { transform(value: any[]): any[] { return value.filter(item => item.active); } }
-
Obserbale used for handling multiple values, asynchronous programming and also event handling processes.
Observables in Angular are a way to handle asynchronous data streams, such as HTTP requests or user inputs. They emit multiple values over time, and you can subscribe to them to receive those values.
Key points:
- Emit multiple values: Unlike Promises, Observables can emit multiple values over time.
- Lazy: They don’t start emitting until subscribed.
- Cancellation: You can cancel an Observable with unsubscribe().
- RxJS Operators: Use operators like map, filter, and switchMap to manipulate the data stream.
Ex:
import { Observable } from 'rxjs'; // Creating an Observable const myObservable = new Observable((observer) => { observer.next('First Value'); observer.next('Second Value'); setTimeout(() => { observer.next('Third Value'); observer.complete(); }, 1000); }); // Subscribing to the Observable myObservable.subscribe({ next(value) { console.log(value); }, error(err) { console.error('Error:', err); }, complete() { console.log('Completed'); } });
- What is interface ?
- What is route Guard ?
- When Angular project is is load which element load first and last ?
- Which compiler used in Angular ?
- Explain Directive and its type ?
- Explain Structure directive ?
- Diffrence b/w Component and Directive ?
- Diffrence b/w promises and Obserable in Angular ?
- Diffrence b/w package.json and package.lock json file n Angular ?
- What is RxJS ?
- Dependency injection in angular ?
- View Encapsulation in angular ?
- Module in angular
- ViewEncapsulation in Angular
- Event Bubbling
- Data types in Angular
- Observable vs promise ?
- Content Projection ?
- Lazy Loading ?
- Describe ng-content,ng-template,ng-container ?
- Sharing the data between components
- Interceptor
- Subject vs behaviour subject
- Angular change detection
- Default vs Onpush change detection
- Route Guard
- Dependency Injection
- CanActive vs canLoad
- Memory leak and prevention method
- Meta tag in HTML
- Position : Absolute vs position : relative
- Display:inline-block vs display:block
- box model in CSS
- Closure and example of closure
- Var vs let keyword
- Rest parameter vs Spread operator
- Data type in javaScript
- Console.log(x);
var x=10;
Comments
Post a Comment