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:
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.
What is ngOnInit? How is it defined?
ngOnInit is a lifecycle hook and a callback method that is run by Angular to indicate that a component has been created. It takes no parameters and returns a void type.
export class MyComponent implements OnInit {
constructor() { }
ngOnInit(): void {
//….
}
}
How to use ngFor in a tag?
The ngFor directive is used to build lists and tables in the HTML templates. In simple terms, this directive is used to iterate over an array or an object and create a template for each element.
<ul>
<li *ngFor = "let items in itemlist"> {{ item }} </li>
</ul>
What are Template forms?
Template-driven approach
What are Reactive forms?
Reactive Form Approach
What is Bootstrap? How is it embedded into Angular?
Bootstrap is a powerful toolkit. It is a collection of HTML, CSS, and JavaScript tools for creating and building responsive web pages and web applications.
There are two ways to embed the bootstrap library into your application.
npm install bootstrap
npm install jquery
What type of DOM does Angular implement?
DOM (Document Object Model) treats an XML or HTML document as a tree structure in which each node is an object representing a part of the document.
Angular uses the regular DOM. This updates the entire tree structure of HTML tags until it reaches the data to be updated. However, to ensure that the speed and performance are not affected, Angular implements Change Detection.
With this, you have reached the end of the article. We highly recommend brushing up on the core concepts for an interview. It’s always an added advantage to write the code in places necessary.
What is Eager and Lazy loading?
Eager loading is the default module-loading strategy. Feature modules under Eager loading are loaded before the application starts. This is typically used for small size applications.
Lazy loading dynamically loads the feature modules when there’s a demand. This makes the application faster. It is used for bigger applications where all the modules are not required at the start of the application.
Why were client-side frameworks like Angular introduced?
Client-side frameworks like Angular were introduced to provide a more responsive user experience. By using a framework, developers can create web applications that are more interactive and therefore provide a better user experience.
Frameworks like Angular also make it easier for developers to create single-page applications (SPAs). SPAs are web applications that only need to load a single HTML page. This makes them much faster and more responsive than traditional web applications.
Overall, client-side frameworks like Angular were introduced in order to improve the user experience of web applications. By making web applications more responsive and easier to develop, they provide a better experience for both developers and users.
How are Angular expressions different from JavaScript expressions?
One major difference between Angular expressions and JavaScript expressions is that Angular expressions are compiled while JavaScript expressions are not. This means that Angular expressions are more efficient since they’re already pre-processed. Additionally, Angular expressions can access scope properties while JavaScript expressions cannot. Finally, Angular expressions support some additional features such as filters and directives which aren’t available in JavaScript expressions.