Angular In-Depth Flashcards
These questions explore more advanced Angular concepts and can help demonstrate your in-depth understanding of the framework during interviews.
What are directives in Angular?
Directives are classes in Angular that allow you to modify the behavior or appearance of elements in the DOM.
What types of directives are there?
Component Directives:
These are the most common and define the structure and behavior of a component.
Structural Directives:
These alter the DOM layout by adding or removing elements (e.g., *ngIf, *ngFor).
Attribute Directives:
These change the appearance or behavior of an element (e.g., ngClass, ngStyle).
What is the role of NgModule in Angular?
NgModule is a decorator that declares an Angular module. It organizes an application into cohesive blocks by defining components, directives, pipes, and services that belong to the module. It also helps configure providers and routing. Every Angular app has at least one root module (AppModule).
What is two-way data binding in Angular, and how is it achieved?
Two-way data binding allows data to flow from the component to the view and vice versa. In Angular, it is achieved using the [(ngModel)] directive. It combines property binding ([ ]) and event binding (( )) into a single expression, keeping the view and model in sync.
<input [(ngModel)]=”username” />
What are pipes in Angular, and how do you use them?
Pipes in Angular are used to transform data in templates. For example, you can use pipes to format dates, currencies, or strings. Angular provides built-in pipes like | date, | uppercase, | lowercase, and you can also create custom pipes by implementing the PipeTransform interface.
<p>{{ user.name | uppercase }}</p>
How do you handle HTTP requests in Angular?
Angular provides the HttpClient module for handling HTTP requests. You can import HttpClientModule in your AppModule and use HttpClient to send GET, POST, PUT, and DELETE requests. It returns an observable, making it easy to handle asynchronous data.
Example of a GET request:
this.http.get(‘api/users’).subscribe((data) => console.log(data));
What is a resolver in Angular routing?
A resolver in Angular is used to prefetch data before the route is activated. It is a service that implements the Resolve interface and is used to retrieve necessary data before rendering the component. Resolvers can prevent a component from loading until the data is available.
export class UserResolver implements Resolve<User> {
resolve(route: ActivatedRouteSnapshot): Observable<User> {
return this.userService.getUser(route.paramMap.get('id'));
}
}</User></User>
What are route guards in Angular?
Route guards are interfaces that control navigation to and from routes based on conditions. There are several types of guards:
- CanActivate: Decides if a route can be activated.
- CanDeactivate: Decides if a route can be left.
- Resolve: Pre-fetches data before the route loads.
- CanLoad: Determines if a module can be loaded lazily.
Guards are implemented as services that return true, false, or an observable/promise that resolves to true or false.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.authService.isAuthenticated();
}
What is the difference between ng-template and ng-container?
ng-template:
This element is used to define an Angular template that isn’t rendered immediately but can be displayed later by Angular with structural directives like *ngIf or *ngFor.
ng-container:
This is a grouping element that doesn’t create an actual DOM element. It’s useful for grouping multiple elements or applying structural directives without adding unnecessary nodes to the DOM.
What is ViewChild in Angular, and how is it used?
ViewChild is a decorator that allows access to a child component, directive, or DOM element from the parent component’s class. It is used to interact with child elements and manipulate their properties or methods.
@ViewChild(‘childComponent’) child: ChildComponent;
ngAfterViewInit() {
this.child.someMethod();
}
What is the purpose of Angular’s async pipe?
The async pipe is used to subscribe to an observable or promise in a template, eliminating the need to subscribe manually in the component class. It automatically unsubscribes when the component is destroyed, which helps prevent memory leaks.
<p>{{ user$ | async }}</p>
What is the difference between AOT and JIT?
Ahead of Time (AOT) compilation converts your code during the build time before the browser downloads and runs that code. This ensures faster rendering to the browser. To specify AOT compilation, include the –aot option with the ng build or ng serve command.
The Just-in-Time (JIT) compilation process is a way of compiling computer code to machine code during execution or run time. It is also known as dynamic compilation. JIT compilation is the default when you run the ng build or ng serve CLI commands.
Explain the @Component Decorator.
TypeScript class is one that is used to create components. This genre of class is then decorated with the “@Component” decorator. The decorato’s purpose is to accept a metadata object that provides relevant information about the component.
import { Component }. from ‘@angular/core’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class Component {
title = ‘example’;
}
The image above shows an App component - a pure TypeScript class decorated with the “@Component” decorator. The metadata object that gets accepted by the decorator provides properties like templateUrl, selector, and others, where the templateUrL property points to an HTML file defining what you see on the application.
What are Services in Angular?
Angular Services perform tasks that are used by multiple components. These tasks could be data and image fetching, network connections, and database management among others. They perform all the operational tasks for the components and avoid rewriting of code. A service can be written once and injected into all the components that use that service.
What are Promises and Observables in Angular?
While both the concepts deal with Asynchronous events in Angular, Promises handle one such event at a time while observables handle a sequence of events over some time.
Promises - They emit a single value at a time. They execute immediately after creation and are not cancellable. They are Push errors to the child promises.
Observables - They are only executed when subscribed to them using the subscribe() method. They emit multiple values over a period of time. They help perform operations like forEach, filter, and retry, among others. They deliver errors to the subscribers. When the unsubscribe() method is called, the listener stops receiving further values.