Chapter 3: Angular and REST API.
Now let’s cover 37 Angular and REST API Interview Questions and Answer.
Question: How do you create new application in Angular using Command line?
Answer: To create a new application in Angular using the command line, we can use following steps:
- First, ensure that you have Node.js installed on your system because Angular requires Node.js to work. You can download it from the official Node.js website.
- Install the Angular CLI (Command Line Interface) globally on your computer by running the following command in your terminal:

- Once the Angular CLI is installed, you can create a new Angular application by running:

- Once the installation is complete, you can navigate into your new application's directory:

- To serve your application locally and open it in a browser, use:

Question: What is the use of 'ng serve' command?
Answer: The ‘ng serve’ command is used to launch the development server and serve an Angular application locally. When you run this command, it compiles the application into an output directory and serves it over a local web server. By default, it watches for any changes to the source files and recompiles the app, automatically refreshing the browser to reflect the latest changes. This makes ‘ng serve’ a useful tool for developers to see the effects of their changes in real time.
Question: What is the component in Angular?
Answer: At Angular, we structure our applications using components. Think of components as reusable blocks that define a part of our user interface: for example, a navigation bar with the main menu, a sidebar, etc.
In Angular, a component is a fundamental building block of the framework. It's essentially a TypeScript class that interacts with the HTML template it's associated with, working as a part of the DOM to control a patch of the screen. Components are decorated with ‘@Component’, which allows you to mark a class as an Angular component and provide additional metadata that determines how the component should be processed, instantiated, and used at runtime.Components are key in Angular because they promote modularity, reusability, and separation of concerns. Each component typically encapsulates its own logic, data, and presentation, making it easy to maintain and test. Components can also communicate with each other to perform complex tasks and build dynamic and interactive user interfaces.
Question: What is the @Component Decorator in Angular?
Answer: The ‘@Component’ decorator is a fundamental part of Angular. It is used to define a component class in Angular and its metadata, which determines how the component should be processed, instantiated, and used at runtime.
The components are responsible for defining both their own internal logic and their appearance.
As discussed components are the main building block of an Angular application, and the ‘@Component’ decorator allows you to associate a TypeScript class with a template that defines a view. A component is made up of three things: a component class that handles data and functionality, an HTML template that determines the UI, and component-specific styles.
The metadata attached to the decorator includes properties like ‘selector’, ‘templateUrl’, ‘template’, ‘styles’, and ‘styleUrls’, among others. Here's what they generally signify:
- ‘selector’: Defines the custom HTML tag where the component will be used.
- ‘templateUrl’: Links to an external file that contains the template of the component.
- ‘template’: Contains inline HTML that represents the view for the component.
- ‘styles’: Contains inline styles that are applied to the component's view.
- ‘styleUrls’: Contains the location of the external files where the component's styles are defined.
By using the ‘@Component’ decorator, Angular knows how to instantiate and use components within the ecosystem of an Angular application, including how to render components to the DOM and how to incorporate them into the application's logic and data flow.
Question: What is the directive in Angular?
Answer: In Angular, a directive is a class with a ‘@Directive’ decorator. A directive is used to add behavior to elements in the DOM. There are three kinds of directives in Angular:
- Components: These are directives with a template and are the most common directive type.
- Attribute directives: These change the appearance or behavior of an element, component, or another directive.
- Structural directives: These change the DOM layout by adding and removing DOM elements.
Here's a simple example of a custom attribute directive that changes the color of the text:

And you would use it in your template like this:

Question: What are the services and pipes in Angular?
Answer: Services and pipes are fundamental concepts in Angular that help in building and managing code in an efficient way.
Services: In Angular, a service is a broad category encompassing any value, function, or feature that an application needs. A typical service is a class with a specific, well-defined purpose. It should do something specific and do it well. Services are commonly used to share data or functionality across components. For instance, you might have a ‘DataService’ that handles data retrieval and persistence, which can be injected into components that need that functionality.
Here's a basic example of an Angular service that retrieves user data:

Pipes: Pipes are simple functions in Angular that transform input values to a desired output format.
They can be used in template expressions to improve the user experience by formatting data in a readable format. Common uses of pipes include formatting dates, numbers, and currencies, or filtering and sorting lists. Here's an example of using the built-in ‘date’ pipe in a component template to format a date object:

Here's a simple custom pipe that appends an exclamation mark to a string:

And you would use it in a template like this:

Question: Why do you use export keyword in Angular classes?
Answer: In Angular, the ‘export’ keyword is used in TypeScript to make classes, interfaces, components, directives, and services available for use in other parts of the application. When you export something, it means you're making it accessible to be imported by another module.
For example, when you create a new component, you export the component class so that you can use it in other modules within your Angular app. If you don't export it, that component will only be accessible within the same file and won't be usable elsewhere, which defeats the purpose of modularity and reusability in a framework like Angular. It's like saying, "Hey, I made this, and I want others to be able to use it too."

Question: What is the use of Selector in Component decorator?
Answer: The selector in an Angular component decorator is essentially the name you give to the component. When you want to use that component in your HTML, you use its selector as the tag name. It's like creating a custom HTML element. For instance, if you have a component with a selector 'app-login', you'd use

Question: What is the use of Selector "app-root" in Component decorator?
Answer: The selector ‘app-root’ in the Angular component decorator is essentially the name you give to the HTML tag where your Angular application will be displayed. It's like the entry point for your app. When Angular initializes, it looks for this selector in the index.html file, and that's where it knows to load the root component of your app. It's the hook between your web page and your Angular application.


html:

Question: What is the use of templateUrl in Component decorator?
Answer: The ‘templateUrl’ property in the Angular Component decorator is used to link an external HTML file to the component. This is where you define the component's view, the HTML that will be displayed in the app. It's a way to keep your template code separate from your JavaScript logic, making it easier to maintain and manage, especially when you have a large, complex view. It's like telling your component where to find its layout blueprint.

Question: What is the use of styleUrls in Component decorator?
Answer: The ‘styleUrls’ property within the Component decorator in Angular is used to specify an array of stylesheet URLs that the component will use. These styles are scoped to the component, meaning they are only applied to this particular component and won't affect the rest of the application. This helps in encapsulating the styles and making sure that components are self-contained.
Here's an example of how you might use ‘styleUrls’ in a component:

In this snippet, ‘styleUrls’ is set to an array containing a single string: ‘'./example.component.css'‘. This means that Angular will apply the styles from ‘example.component.css’ to this component. If you have multiple stylesheets, you can list them all in the array, and Angular will apply them in the order listed.
Question: What is module in Angular?
Answer: In Angular, a module is a fundamental building block that groups together related code such as components, services, directives, pipes, and other modules. It's like a container that bundles the functionalities that are related, which can then be composed with other modules to create an application. Modules in Angular use the ‘@NgModule’ decorator which allows you to define the metadata for the module. This metadata can include declarations, imports, exports, providers, and bootstrap array.
For instance, if we're creating a module for user-related components and services, it could look something like this:
In Angular, a module is a fundamental building block that groups together related code such as components, services, directives, pipes, and other modules. It's like a container that bundles the functionalities that are related, which can then be composed with other modules to create an application. Modules in Angular use the ‘@NgModule’ decorator which allows you to define the metadata for the module. This metadata can include declarations, imports, exports, providers, and bootstrap array.
For instance, if we're creating a module for user-related components and services, it could look something like this:
In Angular, a module is a fundamental building block that groups together related code such as components, services, directives, pipes, and other modules. It's like a container that bundles the functionalities that are related, which can then be composed with other modules to create an application. Modules in Angular use the ‘@NgModule’ decorator which allows you to define the metadata for the module. This metadata can include declarations, imports, exports, providers, and bootstrap array.
For instance, if we're creating a module for user-related components and services, it could look something like this:

Question: What is root module in Angular?
Answer: When we generate a new Angular project, a root module is created by us, which is in charge of launching our application. While this module can be called in any way, it is a convention to call it AppModule.
Question: What is the declaration Array in module in Angular?
Answer: In Angular, the ‘declarations’ array in a module is where you tell Angular which components, directives, and pipes belong to that module. When you generate a new component, directive, or pipe with Angular CLI, it automatically adds it to the ‘declarations’ array of the nearest module.
For example, if you have an ‘AppModule’ and you create a new component called ‘HelloComponent’, your ‘AppModule’ might look something like this:

Question: If we need to call Rest API to fetch data, what we will be using?
Answer: In Angular, to call a REST API and fetch data, you would typically use the HttpClient module. It provides a simplified API for HTTP functionality, making it easy to perform various HTTP requests and handle responses. Hence, we will use a service to communicate with this API.
Question: What is Bootstrap 4?
Answer: Bootstrap is a library of frontend components, beautifully stylized, that allow us to build applications that will be perfectly visualized from any device. Bootstrap 4 is a popular front-end framework that is used for designing and building responsive websites and web applications. It's the fourth major release of the Bootstrap project, which was originally created by Twitter. Bootstrap 4 includes a set of CSS and JavaScript tools that simplify the process of styling web pages, handling layouts, and adding functionality.For example, if you're building a responsive navigation bar in Angular using Bootstrap 4, you might use a combination of Bootstrap classes and Angular components.
Here's a simplified code snippet of what that might look like:

In the Angular component TypeScript file, you'd manage the state for the collapsible navbar:

Question: What is Bootstrap CDN?
Answer: Bootstrap CDN is a Content Delivery Network that serves the Bootstrap library to your application directly from its servers. Instead of downloading Bootstrap files and hosting them on your own server, you can simply include a link to the Bootstrap CDN in your project's HTML head section. This way, you're always using the most updated version of Bootstrap, and it can improve load times since the files may already be cached by the user's browser.
For instance, if you're using Bootstrap in an Angular project, you would include it in your ‘index.html’ file like this:

Question: What is jQuery?
Answer: jQuery is a fast, small, and feature-rich JavaScript library. It's designed to simplify things like HTML document traversal and manipulation, event handling, and animation, which helps developers to write less code. jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications.
For instance, if you want to hide a div with the id of "myDiv" when it's clicked, you would need just a single line of code with jQuery:

Question: What is popper?
Answer: Popper is not directly related to Angular; it's actually a positioning engine used for tooltips and popovers in web applications. It's a library that helps developers position elements on the screen in a way that they will fit into the viewport in the best possible way. For instance, if there's not enough space to display a tooltip above a button because it's too close to the top of the screen, Popper will automatically display it below the button. Popper is often used in conjunction with UI component libraries, some of which may be used with Angular for creating dropdowns, context menus, or tooltips. It's not part of Angular itself but rather an external library that can be integrated into an Angular project.Here's an example of how you might use Popper.
js with Angular when creating a tooltip directive:

Question: How do you create component in Angular from command line?
Answer: To create a component in Angular from the command line, you would typically use the Angular CLI (Command Line Interface). Here's how you would do it:
Once the Angular CLI is installed, you can create a new component by navigating to your Angular project directory in the terminal and running the following command:

Or, for short:

This will create a new directory within the ‘/src/app’ folder with the given component name, along with the four files that make up the component:
- A TypeScript file for the component's logic (‘component-name.component.ts’)- An HTML file for the component's template (‘component-name. component.html’)- A CSS file for the component's styles (‘component-name.component.css’)- A testing specification file (‘component-name.component.spec.ts’)
Here's an example of how the TypeScript file might look for a simple component named ‘example’:

Question: What is scaffold in the programmer or architect world means?
Answer: In the programming context, scaffolding refers to the process of generating the basic structure of a project or a part of a project automatically. This can include things like setting up the basic files, default pieces of code, directories, and configuration settings that are required to start a new project or add a new element to an existing project.
For instance, in the world of web development with Angular, scaffolding is often performed using tools such as Angular CLI (Command Line Interface). When you want to create a new Angular application, you would use the Angular CLI and run a command like:

Similarly, if you want to add a new component to an existing Angular application, you would use a command like:

Question: What is the advantage of creating components using Angular CLI and not manually?
Answer: When you create components using Angular CLI, it offers several advantages over manual creation:
Consistency: Angular CLI ensures that the components are created with a consistent directory structure and coding patterns that are in line with Angular's best practices. This uniformity is crucial for maintaining code quality, especially in large projects with multiple developers.
Efficiency: The CLI automates the repetitive tasks involved in setting up a new component, such as creating the files, importing the necessary modules, and setting up the initial boilerplate code. This saves developers a significant amount of time and effort.
Integration: Components created with Angular CLI are automatically declared in the module, ensuring that they are ready to use and properly integrated into the Angular ecosystem. This avoids common errors that can occur when manually declaring and wiring up components.
Tooling: Angular CLI provides additional tooling support like linting, building, testing, and serving applications, which can all be configured to work seamlessly with the components created by it.
Updates: Angular CLI makes it easier to update components to the latest Angular version through automated migration scripts.
For example, creating a new component manually requires you to create at least four files: the component class file, the HTML template, the CSS stylesheet, and the test spec file. With Angular CLI, you can generate all these files with correct boilerplate code with a single command:

Or the shorthand:

Question: What do you mean by linters or linting?
Answer: Linters, or linting tools, are programs that analyze code for potential errors, bugs, stylistic errors, and suspicious constructs. They are a form of static code analysis, meaning they do not require the code to be executed to find issues. Linting helps maintain a consistent code style, improve code quality, and find errors early in the development process, which can save time and resources. For example, in the context of Angular development, a popular linter used is TSLint, which checks TypeScript code. However, TSLint has been deprecated in favor of ESLint, which now has great support for TypeScript as well.Let's say you have an Angular component, and you accidentally created an unused variable.
A linter would flag this as a warning or error, depending on the configuration. Here’s a small code snippet with an unused variable:

Question: What is routing in Angular components or module or application?
Answer: In an Angular application, routing is the capability provided by the Angular Router, which allows us to define navigation paths between different components. This enables us to navigate from one view to another as users perform application tasks.
To implement routing in Angular, we first need to set up routes that associate path strings with components.
We define these in our ‘RouterModule’ which we then import into our application module. Here’s a simple example of how routing might be configured in an Angular app:

To navigate to a route programmatically, you can inject the ‘Router’ service into a component and call its ‘navigate’ method:

Question: How do you define a route where is no path defined?
Answer: In Angular, a route where no path is defined is typically referred to as a "wildcard" route. This kind of route is defined using the ‘**’ path in the route configuration and is used to match any URL that doesn't match any other routes defined in the routing module. It's often used for displaying a 404 Not Found page or redirecting to another route.
Here's an example of how you might define such a route in your routing module (‘app-routing.module.ts’):

Question: What is router-outlet in Angular?
Answer: The ‘router-outlet’ in Angular acts as a placeholder that Angular dynamically fills based on the current router state. It's where the content of the route your user is navigating to will be displayed. When you define routes in Angular, you're mapping paths to components. The ‘router-outlet’ is the place in the template where this mapping gets realized, and the components get rendered.
For example, in your main app component template, you might have something like this:

Question: What are services in Angular?
Answer: Services in Angular are a fundamental concept for managing common functionality across various parts of an application. A service is essentially a class with a specific purpose and typically involves sharing data or functions between components. Instead of duplicating code, you create a service and inject it into the components that need that functionality. This is in line with the DRY (Don't Repeat Yourself) principle and helps in maintaining the code.For instance, if you have an application that needs to fetch user data from a server, you would create a service that handles the HTTP requests. This service could be injected into any component that needs to access user data.
Here's a basic example of a service that retrieves user data from an API:

Question: How do you create Service in Angular?
Answer: Creating a service in Angular is typically done using the Angular CLI (Command Line Interface). You can generate a new service by using the command ‘ng generate service service-name’ or the shorthand ‘ng g s service-name’. This will create a service file with the necessary boilerplate code. Here's a simple example:

In the ‘@Injectable’ decorator, the ‘providedIn: 'root'‘ metadata means that the service is available throughout the application, and Angular will create a single, shared instance of ‘DataService’.
You can then inject this service into any component or other service like this:

Question: What is the difference between endpoint, API and microservice?
Answer: In an interview setting, explaining these concepts succinctly and with practical examples would be key. An endpoint in web development is the specific address or URL of a service on the internet where certain operations can be performed. It's like the specific address you would send a letter to.
For example, in Angular, you might have a service that communicates with an endpoint like ‘https: //api.example.com/users’ to retrieve user information.
An API (Application Programming Interface) is a set of rules and definitions that allows different software applications to communicate with each other. It acts as a contract between two parties, the provider and the consumer, dictating how requests and responses are formatted. In Angular, you would typically use the ‘HttpClient’ module to make API calls.

Question: What is in-memory API?
Answer: In-memory API in the context of Angular generally refers to a simulation of a backend API within the browser's memory. It's used primarily for testing and prototyping when a real API isn't available. By using an in-memory API, developers can mimic CRUD operations without the need to set up a real server backend.
Here's a quick example: let's say you're building a service in Angular that deals with user data. Instead of calling a real API, you can use Angular's ‘HttpClientInMemoryWebApiModule’ to simulate responses. First, you install the in-memory web API package:

Then, you set up a service to simulate the API:

And in your module, you would import the ‘HttpClientInMemoryWebApiModule’ and initialize it with your ‘InMemoryDataService’:

Question: What does it mean when someone says rudimentary function?
Answer: When someone refers to a "rudimentary function" in the context of Angular or programming in general, they are typically talking about a basic or fundamental function that performs a simple task without any complex logic or dependencies. In Angular, a rudimentary function might be a simple method within a component class that performs a straightforward operation like toggling a boolean value or setting a property when called.
Here's a code example of a rudimentary function in an Angular component that toggles a boolean property:

Question: What is the use of Observable?
Answer: In an Angular context, Observables play a crucial role in handling asynchronous data. They come from the RxJS library, which is a set of tools for reactive programming. An Observable is essentially a stream of data that you can subscribe to. This pattern is particularly useful when dealing with tasks that are inherently asynchronous, like HTTP requests, where you send out a request and eventually receive a response, but you don't want to block your application while waiting for this response.
Here's a basic code example of how you might use an Observable in Angular:

Question: In Angular, how to define global style?
Answer: In Angular, global styles can be defined in a few different ways, but the most common approach is to use the ‘styles.css’ or ‘styles.scss’ file which is located at the root of the ‘src’ folder in your Angular project. This stylesheet is automatically included in the build configuration via the ‘angular. json’ file, and styles defined here will be applied globally across your application.For instance, if you want to set a global font or background for all the components in your application, you would add the CSS rules to this file. Here's an example of how you might define some global styles in ‘styles.
css’:

Here's how you might add a style file to the ‘angular.json’:

Question: In Angular, what is ActivatedRoute component?
Answer: The ‘ActivatedRoute’ component in Angular is a service provided by the ‘@angular/router’ package that contains the information about a route associated with a component loaded into an Angular application. This service has properties that contain information such as the URL, the parameters, the data passed to the route, and the state of the route among others.
For example, if you need to access the route parameters, you can inject the ‘ActivatedRoute’ service into your component constructor and use it like so:

" Here's a code snippet to illustrate its use in a more straightforward way:

Question: What is Bootstrap Card component, why you want to use?
Answer: The Bootstrap Card component is a flexible and extensible content container. It includes options for headers and footers, a wide variety of content, contextual background colors, and powerful display options. In Angular applications, Cards are used for placing content in a neat and concise manner, making it easy to arrange elements like images, texts, links, and buttons. Using Cards enhances the visual quality of the application and contributes to a better user experience by organizing content in an easily digestible format. They can be dynamically generated and manipulated using Angular's powerful data binding and component logic.
Question: What is Bootstrap, what is containers?
Answer: Bootstrap is a popular front-end framework that's used to create responsive and mobile-first web pages. It consists of design templates for typography, forms, buttons, navigation, and other interface components, as well as optional JavaScript extensions. Bootstrap is known for its grid system, which uses a series of containers, rows, and columns to layout and align content.
Containers are the most basic layout element in Bootstrap and are required when using the default grid system. They are used to contain, pad, and (sometimes) center the content within them. There are two types of containers in Bootstrap:
- .container, which provides a responsive fixed width container,- . container-fluid, which provides a full width container, spanning the entire width of the viewport.When using the container class, we will obtain an element with a fixed width, but whose value for the max-width property will change with each breakpoint.
Question: What is the use of 'ngIf' directive?
Answer: The ‘ngIf’ directive in Angular is a built-in structural directive that's used to add or remove an element from the DOM based on a condition. Essentially, it helps in conditionally rendering parts of the UI. For example, consider a situation where you want to display a message only if a user is logged in.
You could use ‘ngIf’ like this:

ReadioBook.com