Interview Preparation
Practice real interview questions with detailed answers
77 Questions
Easy
21 questions
ANGULAR.JS
#1.1
Q1:
What is Angular?
Ans:
Angular is a TypeScript-based, open-source front-end framework maintained by Google for building single-page applications, providing a complete solution including templating, dependency injection, routing, forms, and HTTP handling out of the box.
ANGULAR.JS
#1.2
Q2:
What is the difference between AngularJS and Angular?
Ans:
AngularJS (version 1.x) is the original JavaScript-based MVC framework released in 2010, while Angular (version 2 and above) is a complete rewrite in TypeScript with a component-based architecture, improved performance, and mobile support; they are largely incompatible with each other.
ANGULAR.JS
#1.3
Q3:
Why does Angular use TypeScript?
Ans:
TypeScript adds static typing, interfaces, and decorators to JavaScript, enabling compile-time error checking, better tooling and autocompletion, and clearer contracts between components, which Angular relies on heavily for features like dependency injection metadata.
ANGULAR.JS
#1.4
Q4:
What is a component in Angular?
Ans:
A component is the fundamental building block of an Angular UI, defined by a class decorated with @Component that specifies an HTML template, associated styles, and a selector used to instantiate it within other templates.
Code Example
@Component({
selector: 'app-hero',
templateUrl: './hero.component.html'
})
export class HeroComponent {}
ANGULAR.JS
#1.5
Q5:
What is a module (NgModule) in Angular?
Ans:
An NgModule is a class decorated with @NgModule that groups related components, directives, pipes, and services together, declaring what belongs to the module and what external modules it depends on via the imports array.
Code Example
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule {}
ANGULAR.JS
#1.6
Q6:
What is data binding in Angular?
Ans:
Data binding is the mechanism that synchronizes data between a component's TypeScript class and its HTML template; Angular supports interpolation, property binding, event binding, and two-way binding.
ANGULAR.JS
#1.7
Q7:
What is interpolation in Angular?
Ans:
Interpolation uses double curly braces {{ }} to embed a component's property value directly into the template's text content, evaluated and inserted as a string.
Code Example
<p>Hello, {{ userName }}!</p>
ANGULAR.JS
#1.8
Q8:
What is property binding in Angular?
Ans:
Property binding, using square brackets [property], sets a DOM element's property or a directive/component's input property to the value of a component's expression, flowing data one-way from the class to the template.
Code Example
<img [src]="imageUrl">
ANGULAR.JS
#1.9
Q9:
What is event binding in Angular?
Ans:
Event binding, using parentheses (event), listens for a DOM event (like click) or a custom component event and calls a method on the component class when it fires.
Code Example
<button (click)="onSave()">Save</button>
ANGULAR.JS
#1.10
Q10:
What is two-way data binding in Angular?
Ans:
Two-way binding, using the banana-in-a-box syntax [(ngModel)], combines property and event binding so that changes in the UI update the component property and changes to the property update the UI simultaneously.
Code Example
<input [(ngModel)]="userName">
ANGULAR.JS
#1.11
Q11:
What does *ngIf do?
Ans:
*ngIf is a structural directive that conditionally adds or completely removes an element (and its subtree) from the DOM based on a boolean expression, unlike CSS-based hiding which keeps the element in the DOM.
Code Example
<div *ngIf="isLoggedIn">Welcome back!</div>
ANGULAR.JS
#1.12
Q12:
What does *ngFor do?
Ans:
*ngFor is a structural directive that repeats a template for each item in a collection, commonly used with the index and trackBy for performance optimization.
Code Example
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
ANGULAR.JS
#1.13
Q13:
What is ngClass used for?
Ans:
ngClass dynamically adds or removes CSS classes on an element based on an expression, object, or array, letting class names change in response to component state.
Code Example
<div [ngClass]="{ active: isActive, disabled: isDisabled }"></div>
ANGULAR.JS
#1.14
Q14:
What is ngStyle used for?
Ans:
ngStyle dynamically sets inline CSS styles on an element based on an object whose keys are style properties and values are expressions evaluated from the component.
Code Example
<div [ngStyle]="{ color: textColor, 'font-size.px': fontSize }"></div>
ANGULAR.JS
#1.15
Q15:
What are pipes in Angular?
Ans:
Pipes are simple functions used in templates to transform displayed data, such as formatting dates, numbers, or currency, applied using the pipe operator (|).
Code Example
<p>{{ birthday | date:'longDate' }}</p>
<p>{{ price | currency:'USD' }}</p>
ANGULAR.JS
#1.16
Q16:
What are Angular services used for?
Ans:
Services are classes with a focused, well-defined purpose (like fetching data, logging, or sharing state) that are injected into components or other services, promoting separation of concerns and code reuse instead of putting business logic directly in components.
ANGULAR.JS
#1.17
Q17:
What is the HttpClient module used for?
Ans:
HttpClient is Angular's built-in service for making HTTP requests, returning Observables for requests, and supporting features like interceptors, typed responses, and testing utilities via HttpClientTestingModule.
Code Example
this.http.get<User[]>('/api/users').subscribe(users => this.users = users);
ANGULAR.JS
#1.18
Q18:
What is the difference between @Input and @Output?
Ans:
@Input marks a property that receives data from a parent component via property binding, while @Output marks an EventEmitter property that lets a component emit custom events upward to a parent, which listens for them using event binding.
Code Example
@Input() userName: string;
@Output() save = new EventEmitter<void>();
ANGULAR.JS
#1.19
Q19:
What is Angular's Router used for?
Ans:
The Angular Router enables navigation between different views/components based on the URL in a single-page application, supporting features like route parameters, guards, lazy loading, and nested/child routes.
Code Example
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'users/:id', component: UserDetailComponent }
];
ANGULAR.JS
#1.20
Q20:
What is the purpose of the Angular CLI?
Ans:
The Angular CLI is a command-line tool that scaffolds new projects, generates components/services/modules with the correct boilerplate and file structure, and manages building, testing, and serving the application through commands like ng generate, ng build, and ng serve.
Code Example
ng generate component user-profile
ng build --configuration production
ng serve
ANGULAR.JS
#1.21
Q21:
What is the difference between Angular and React at a high level?
Ans:
Angular is a complete, opinionated framework providing routing, forms, HTTP client, and dependency injection out of the box using TypeScript and a component/module system, while React is a focused UI library that requires selecting and integrating separate libraries for routing, state management, and other concerns.
Medium
37 questions
ANGULAR.JS
#2.1
Q1:
What are standalone components in Angular?
Ans:
Standalone components (introduced in Angular 14+ and the default since Angular 17+) are components that don't need to be declared in an NgModule; they specify their own imports directly, simplifying the module system and reducing boilerplate.
Code Example
@Component({
selector: 'app-hero',
standalone: true,
imports: [CommonModule],
template: `<p>Hero</p>`
})
export class HeroComponent {}
ANGULAR.JS
#2.2
Q2:
What is the difference between structural and attribute directives?
Ans:
Structural directives (prefixed with *, like *ngIf and *ngFor) change the DOM structure by adding or removing elements, while attribute directives (like ngClass and ngStyle) change the appearance or behavior of an existing element without adding or removing elements.
ANGULAR.JS
#2.3
Q3:
What is trackBy used for in *ngFor?
Ans:
trackBy provides a function that returns a unique identifier for each item in a list, allowing Angular's change detection to track items by identity rather than object reference, avoiding unnecessary DOM re-creation when the list is updated.
Code Example
trackById(index: number, item: Item): number {
return item.id;
}
ANGULAR.JS
#2.4
Q4:
How do you create a custom pipe in Angular?
Ans:
A custom pipe is created by implementing the PipeTransform interface in a class decorated with @Pipe, defining a transform() method that takes the input value and returns the transformed output.
Code Example
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 20): string {
return value.length > limit ? value.slice(0, limit) + '...' : value;
}
}
ANGULAR.JS
#2.5
Q5:
What is dependency injection in Angular?
Ans:
Dependency injection is a design pattern where a class's dependencies (like services) are provided to it from an external injector rather than being created inside the class itself, which Angular implements through its hierarchical injector system and the @Injectable decorator.
Code Example
@Injectable({ providedIn: 'root' })
export class UserService {
getUsers() { return this.http.get('/api/users'); }
}
ANGULAR.JS
#2.6
Q6:
What does providedIn: 'root' mean when declaring a service?
Ans:
providedIn: 'root' registers the service with the application's root injector, making it a singleton available throughout the entire application without needing to list it in a module's providers array, and enables tree-shaking if the service is never injected anywhere.
ANGULAR.JS
#2.7
Q7:
What is RxJS and how does Angular use it?
Ans:
RxJS is a library for reactive programming using Observables; Angular uses it extensively for asynchronous operations like HTTP requests (via HttpClient), event handling, reactive forms, and the Router, allowing composition of async data streams using operators like map, filter, and switchMap.
Code Example
this.http.get('/api/data').pipe(
map(res => res.items),
filter(items => items.length > 0)
).subscribe(items => this.items = items);
ANGULAR.JS
#2.8
Q8:
What is the difference between an Observable and a Promise?
Ans:
A Promise resolves a single value once and cannot be cancelled, while an Observable can emit multiple values over time, supports cancellation via unsubscribe, and provides a rich set of composable operators for transforming, combining, and filtering streams of data.
ANGULAR.JS
#2.9
Q9:
What is the async pipe used for?
Ans:
The async pipe subscribes to an Observable or Promise directly within a template, automatically displaying emitted values and automatically unsubscribing when the component is destroyed, removing the need for manual subscription management.
Code Example
<div *ngIf="user$ | async as user">{{ user.name }}</div>
ANGULAR.JS
#2.10
Q10:
Why is it important to unsubscribe from Observables in Angular?
Ans:
Failing to unsubscribe from long-lived Observables (like those from event listeners or manual HTTP subscriptions kept open) can cause memory leaks, since the subscription callback keeps a reference to the component even after it has been destroyed.
Code Example
ngOnDestroy() {
this.subscription.unsubscribe();
}
ANGULAR.JS
#2.11
Q11:
What are HTTP interceptors in Angular?
Ans:
Interceptors are services implementing HttpInterceptor that sit in the HTTP request/response pipeline, letting you globally modify outgoing requests (like adding auth headers) or incoming responses (like handling errors) before they reach the calling code.
Code Example
intercept(req: HttpRequest<any>, next: HttpHandler) {
const authReq = req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
return next.handle(authReq);
}
ANGULAR.JS
#2.12
Q12:
What is Angular's component lifecycle?
Ans:
A component progresses through a sequence of lifecycle hooks managed by Angular: ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, and finally ngOnDestroy, each letting you hook into a specific moment of the component's existence.
ANGULAR.JS
#2.13
Q13:
What is ngOnInit used for and how does it differ from a constructor?
Ans:
ngOnInit is called once, right after Angular has initialized all data-bound input properties, making it the right place for initialization logic that depends on those inputs, whereas the constructor is meant only for basic class setup and dependency injection, and runs before inputs are set.
Code Example
ngOnInit() {
this.loadData();
}
ANGULAR.JS
#2.14
Q14:
What is ngOnChanges used for?
Ans:
ngOnChanges is called whenever one or more data-bound input properties change, receiving a SimpleChanges object describing the previous and current values, useful for reacting to specific input updates.
Code Example
ngOnChanges(changes: SimpleChanges) {
if (changes['userId']) this.loadUser();
}
ANGULAR.JS
#2.15
Q15:
What is ngOnDestroy used for?
Ans:
ngOnDestroy is called just before Angular destroys a component or directive, making it the place to clean up resources like unsubscribing from Observables, clearing timers, or detaching event listeners to prevent memory leaks.
ANGULAR.JS
#2.16
Q16:
How does a child component communicate with its parent in Angular?
Ans:
A child component emits a custom event using an @Output EventEmitter, which the parent template listens for using event binding syntax and handles with a method defined in the parent's class.
Code Example
// child
@Output() itemSelected = new EventEmitter<Item>();
select(item: Item) { this.itemSelected.emit(item); }
// parent template
<app-child (itemSelected)="onItemSelected($event)"></app-child>
ANGULAR.JS
#2.17
Q17:
What is @ViewChild used for?
Ans:
@ViewChild lets a component get a reference to a child component, directive, or DOM element within its own template, allowing direct access to its properties and methods after the view has been initialized.
Code Example
@ViewChild('nameInput') nameInput: ElementRef;
ngAfterViewInit() {
this.nameInput.nativeElement.focus();
}
ANGULAR.JS
#2.18
Q18:
What is content projection in Angular?
Ans:
Content projection, implemented with the tag, lets a component render content passed to it from its parent between its opening and closing tags, similar to React's children prop, enabling flexible, reusable wrapper components.
Code Example
// card.component.html
<div class="card"><ng-content></ng-content></div>
// usage
<app-card><p>Hello</p></app-card>
ANGULAR.JS
#2.19
Q19:
What is change detection in Angular?
Ans:
Change detection is the mechanism Angular uses to keep the DOM in sync with the component's data by checking for changes and re-rendering the affected parts of the template; by default, it runs for every component in the tree whenever an event, timer, or HTTP response triggers Zone.js.
ANGULAR.JS
#2.20
Q20:
What are route guards in Angular?
Ans:
Route guards are interfaces (like CanActivate, CanDeactivate, and CanLoad) that let you control whether navigation to or away from a route is allowed, commonly used for authentication checks or preventing navigation away from a form with unsaved changes.
Code Example
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn() || inject(Router).parseUrl('/login');
};
ANGULAR.JS
#2.21
Q21:
What is lazy loading in Angular and why is it used?
Ans:
Lazy loading defers loading a feature module's (or standalone component's) JavaScript bundle until the user actually navigates to a route that needs it, reducing the initial bundle size and improving startup performance.
Code Example
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
ANGULAR.JS
#2.22
Q22:
What is the difference between template-driven forms and reactive forms?
Ans:
Template-driven forms use directives like ngModel directly in the HTML template with the form structure implicitly created by Angular, while reactive forms define the form's structure and validation explicitly in the component class using FormGroup and FormControl, offering more predictability, testability, and control for complex forms.
ANGULAR.JS
#2.23
Q23:
What is FormBuilder used for?
Ans:
FormBuilder is a service that provides convenient shorthand syntax for creating FormGroup, FormControl, and FormArray instances, reducing the boilerplate needed when constructing reactive forms.
Code Example
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
ANGULAR.JS
#2.24
Q24:
What are Validators in Angular reactive forms?
Ans:
Validators are functions attached to a FormControl that check the control's value and return an error object if invalid or null if valid; Angular provides built-in validators like required, minLength, and pattern, and also supports custom validator functions.
Code Example
email: ['', [Validators.required, Validators.email]]
ANGULAR.JS
#2.25
Q25:
What is dependency injection's providers array used for?
Ans:
The providers array (in an @NgModule, @Component, or @Injectable) tells Angular's injector how to create a particular dependency—directly with the class, via a factory function, or with a specific value—and at what scope it should be available.
Code Example
providers: [{ provide: ApiService, useClass: MockApiService }]
ANGULAR.JS
#2.26
Q26:
What is a singleton service in Angular?
Ans:
A singleton service is a service of which only one instance exists for a given injector scope (commonly the whole app when using providedIn: 'root'), ensuring all components that inject it share the same state and instance.
ANGULAR.JS
#2.27
Q27:
How does Angular protect against XSS attacks by default?
Ans:
Angular automatically sanitizes values interpolated into the DOM, stripping out potentially dangerous HTML, styles, or URLs by default, so developers must explicitly opt out via DomSanitizer if they intentionally need to render trusted raw HTML.
ANGULAR.JS
#2.28
Q28:
What is the purpose of ng-container?
Ans:
ng-container is a logical, non-rendering wrapper element that groups multiple elements or applies a structural directive without adding an extra node to the actual DOM, useful when you need *ngIf on multiple sibling elements at once.
Code Example
<ng-container *ngIf="showDetails">
<h2>Title</h2>
<p>Description</p>
</ng-container>
ANGULAR.JS
#2.29
Q29:
What testing tools does Angular use by default?
Ans:
Angular CLI projects are set up by default with Jasmine as the testing framework and Karma as the test runner, though Jest has become a popular alternative; TestBed is used to configure and create testing modules for isolating and testing components and services.
Code Example
TestBed.configureTestingModule({ declarations: [MyComponent] });
const fixture = TestBed.createComponent(MyComponent);
ANGULAR.JS
#2.30
Q30:
What is TestBed used for in Angular testing?
Ans:
TestBed is Angular's primary testing utility that creates a dynamically constructed Angular testing module, letting you configure providers, declarations, and imports to create component fixtures and test them in an environment resembling the real application.
ANGULAR.JS
#2.31
Q31:
What is the difference between a module and a standalone component architecture?
Ans:
The traditional NgModule-based architecture organizes the app into cohesive units declared via @NgModule, while the standalone architecture (default from Angular 17+) lets components, directives, and pipes declare their own dependencies directly, eliminating most or all NgModules and simplifying the mental model.
ANGULAR.JS
#2.32
Q32:
What is the inject() function used for in Angular?
Ans:
inject() is a function that can retrieve a dependency from Angular's injection context outside of a constructor, commonly used in functional route guards, resolvers, and standalone component setup code where a class constructor isn't available.
Code Example
export const authGuard: CanActivateFn = () => {
return inject(AuthService).isLoggedIn();
};
ANGULAR.JS
#2.33
Q33:
What is a directive in Angular?
Ans:
A directive is a class that can attach additional behavior to elements in the DOM; Angular has component directives (with a template), structural directives (that change DOM layout, like *ngIf), and attribute directives (that change appearance or behavior, like ngClass).
ANGULAR.JS
#2.34
Q34:
How do you create a custom attribute directive in Angular?
Ans:
A custom attribute directive is created using the @Directive decorator with a selector, and typically injects ElementRef and Renderer2 to safely manipulate the host element's properties or styles.
Code Example
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(el: ElementRef, renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'backgroundColor', 'yellow');
}
}
ANGULAR.JS
#2.35
Q35:
How do you optimize the performance of a large Angular application?
Ans:
Common strategies include enabling OnPush change detection, lazy-loading feature modules or routes, using trackBy with *ngFor, avoiding heavy computation directly in templates, using pure pipes instead of methods in bindings, and adopting Signals to reduce reliance on Zone.js-triggered global change detection.
ANGULAR.JS
#2.36
Q36:
What is the significance of the environment.ts files in an Angular project?
Ans:
environment.ts and environment.prod.ts hold environment-specific configuration values (like API URLs), and the Angular CLI's build system automatically swaps in the appropriate file based on the build configuration used (e.g., ng build --configuration production).
ANGULAR.JS
#2.37
Q37:
What is a barrel file in Angular projects?
Ans:
A barrel file is an index.ts file that re-exports multiple modules from a directory, allowing consumers to import several related classes from a single, shorter path rather than importing each file individually.
Code Example
// index.ts
export * from './user.service';
export * from './user.model';
Hard
19 questions
ANGULAR.JS
#3.1
Q1:
What is the difference between a pure pipe and an impure pipe?
Ans:
A pure pipe only re-executes when Angular detects a pure change to its input (a different object reference or primitive value), while an impure pipe (declared with pure: false) re-executes on every change detection cycle regardless of whether the input reference changed, which is more expensive but necessary for mutable data like arrays being pushed to.
ANGULAR.JS
#3.2
Q2:
What is the injector hierarchy in Angular?
Ans:
Angular maintains a tree of injectors mirroring the component tree; when a component requests a dependency, Angular looks for a provider starting at that component's own injector and walks up through ancestor injectors until it finds one, allowing different scopes (root, module, or component-level) to provide different instances.
ANGULAR.JS
#3.3
Q3:
What is the difference between @ViewChild and @ContentChild?
Ans:
@ViewChild queries elements defined in the component's own template, while @ContentChild queries elements that were projected into the component from its parent via .
ANGULAR.JS
#3.4
Q4:
What is the difference between ChangeDetectionStrategy.Default and OnPush?
Ans:
The Default strategy checks a component on every change detection cycle triggered anywhere in the app, while OnPush restricts checks to only run when an @Input reference changes, an event originates from within the component, or an Observable bound with async emits, significantly improving performance for large applications.
Code Example
@Component({
selector: 'app-item',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ItemComponent {}
ANGULAR.JS
#3.5
Q5:
What is Zone.js and what role does it play in Angular?
Ans:
Zone.js is a library that patches asynchronous browser APIs (like setTimeout, promises, and event listeners) so Angular can automatically know when to run change detection after any async operation completes, without the developer having to trigger it manually.
ANGULAR.JS
#3.6
Q6:
What are Angular Signals?
Ans:
Signals (introduced in Angular 16+ and stabilized further in later versions) are a reactive primitive that wraps a value and notifies consumers when it changes, enabling fine-grained, more predictable reactivity and eventually reducing reliance on Zone.js for change detection.
Code Example
const count = signal(0);
count.set(count() + 1);
const doubled = computed(() => count() * 2);
ANGULAR.JS
#3.7
Q7:
What is the difference between a signal and an Observable?
Ans:
A signal is a synchronous, always-has-a-current-value reactive primitive read by calling it as a function, designed for UI state and integrated directly with change detection, while an Observable models an asynchronous stream of values over time and requires explicit subscription/unsubscription.
ANGULAR.JS
#3.8
Q8:
What is a resolver in Angular routing?
Ans:
A resolver implements the Resolve interface to pre-fetch data before a route is activated, ensuring the component has the data available immediately upon initialization rather than showing an empty state while fetching.
ANGULAR.JS
#3.9
Q9:
How do you create a custom validator in Angular?
Ans:
A custom validator is a function that takes an AbstractControl and returns either null (valid) or a ValidationErrors object; it's attached to a FormControl alongside built-in validators.
Code Example
function forbiddenNameValidator(control: AbstractControl): ValidationErrors | null {
return control.value === 'admin' ? { forbiddenName: true } : null;
}
ANGULAR.JS
#3.10
Q10:
What is a FormArray used for?
Ans:
FormArray manages a dynamic, variable-length collection of FormControl, FormGroup, or nested FormArray instances, useful for forms where the user can add or remove repeated sets of fields, like a list of phone numbers.
ANGULAR.JS
#3.11
Q11:
What is Ahead-of-Time (AOT) compilation in Angular?
Ans:
AOT compilation converts Angular templates and components into efficient JavaScript during the build process (before the browser downloads the app), as opposed to Just-in-Time (JIT) compilation which does this in the browser at runtime; AOT results in faster rendering, smaller bundles, and earlier template error detection.
ANGULAR.JS
#3.12
Q12:
What is the difference between JIT and AOT compilation?
Ans:
JIT compiles the application in the browser at runtime, which is slower to start and ships the Angular compiler in the bundle, while AOT compiles during the build step on the server/CI machine, producing a smaller, faster-starting bundle that doesn't need to include the compiler; Angular CLI uses AOT by default for production builds.
ANGULAR.JS
#3.13
Q13:
What is the difference between providedIn: 'root' and listing a service in a module's providers array?
Ans:
providedIn: 'root' registers the service as a tree-shakable, application-wide singleton without needing to be listed anywhere else, while adding a service to a specific module's or component's providers array scopes a separate instance of that service to that module or component subtree.
ANGULAR.JS
#3.14
Q14:
What is the purpose of Angular's DomSanitizer?
Ans:
DomSanitizer sanitizes values (like HTML, URLs, or styles) that would otherwise be automatically escaped by Angular for security, allowing developers to explicitly mark content as safe to bypass Angular's built-in XSS protection when necessary and appropriate.
Code Example
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(rawHtml);
ANGULAR.JS
#3.15
Q15:
What is the purpose of the ng-template directive?
Ans:
ng-template defines a template fragment that isn't rendered by default; it can be rendered conditionally or repeatedly using structural directives, ngIf/else, or programmatically via a ViewContainerRef and TemplateRef.
Code Example
<ng-template #loading><p>Loading...</p></ng-template>
<div *ngIf="data; else loading">{{ data }}</div>
ANGULAR.JS
#3.16
Q16:
What are Angular animations and how are they implemented?
Ans:
Angular's animation module lets you define state-based transitions and keyframe animations declaratively using the @angular/animations package, triggered by binding an animation trigger to a component property, without relying on external CSS animation libraries.
Code Example
trigger('fade', [
state('void', style({ opacity: 0 })),
transition(':enter', animate('300ms'))
])
ANGULAR.JS
#3.17
Q17:
What is the difference between Angular's constructor injection and inject()?
Ans:
Constructor injection declares dependencies as constructor parameters and is the traditional class-based approach, while inject() retrieves a dependency imperatively from within an injection context (like a factory function or a functional guard), useful in places where defining a class isn't convenient.
ANGULAR.JS
#3.18
Q18:
What is the purpose of Renderer2 in Angular?
Ans:
Renderer2 provides an abstraction for manipulating DOM elements (setting styles, attributes, or classes) in a platform-independent way, which is safer than directly accessing nativeElement since it works correctly across server-side rendering and web worker contexts.
ANGULAR.JS
#3.19
Q19:
What is Angular Universal used for?
Ans:
Angular Universal is Angular's server-side rendering solution, rendering the application to static HTML on the server for faster initial page loads and improved SEO, then hydrating it on the client once JavaScript loads.