Tech Point Fundamentals

Saturday, November 25, 2023

Angular Interview Questions and Answers - Part 10

Angular Interview Questions and Answers - Part 10

Angular-Interview-Questions-And-Answers

Angular is a popular open-source single-page application design framework and development platform. It is a robust front-end JavaScript framework that is widely used for front-end application development. Nowadays Angular is very famous as a frontend technology so it is very common for the interview point as well. 

Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 10th part of the Angular Interview Questions and Answer series.

I will highly recommend to please do visit the following parts before continuing to this part:


Please do visit our YouTube Channel here to watch Interview Questions and answers and important technology videos.

In this part we will discuss the following Important Angular Interview Questions:

Q110. What are the Components in Angular? How can you create a component in Angular? 
Q111. What are Modules in Angular? What are the advantages of modules in Angular?
Q112. What is declarable in Angular? Where is it defined in Angular?
Q113. What are the different types of Modules in Angular? 
Q114. What is the difference between RootModule vs. FeatureModule in Angular?
Q115. What is CommonModule in Angular? What is the difference between CommonModule vs. BrowserModule in Angular?
Q116. What will happen if browserModule is used in a Feature Module?
Q117. What will happen if you import the same module twice in Angular? How can you avoid circular module dependency in Angular?
Q118. What is the difference between a Component vs. Module in Angular?
Q119. What is the difference between Component vs. Directive in Angular?
Q120. What is the difference between NgModule vs. JavaScript Module?
Q121. How does Angular find components, directives, and pipes in a template? What is a template reference?

Angular Interview Questions and Answers: Part 10


Q110. What are the Components in Angular? How can you create a component in Angular? 

Components are the fundamental building blocks of the user interface in Angular applications. Components are the smallest, self-contained units in an Angular application. They are typically used to represent a view or UI element, such as a button or a form input field. So it is basically a custom HTML element or template that only Angular can understand. 

A component is defined using the @Component decorator. Every component consists of three parts, the template which loads the view for the component, a stylesheet which defines the look and feel for the component, and a class that contains the business logic for the component.

An Angular application is a tree of Angular components. Actually, angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per element in a template.

Angular components are isolated, so styles and code from one component do not affect other components as they get namespaced by the compiler. These components are then pieced together by the Angular framework to build the user interface for the browser to render. An Angular component consists of its own HTML, CSS, and JavaScript for a specific portion of a user interface. 

To create a component inside the command terminal, navigate to the directory of the application created, and run the following command:

ng generate component my-component 

-OR-

ng g c my-component 

When you use the above CLI command:


angular-component

The command will create 4 files i.e. html file, ts file, spec.ts file, and design/css file. 

import { Component } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent {
}

Also, it updates one important file i.e. app.module.ts file in which it registers this newly created component under the declarations section of @NgModule so that it is available for use across other components.

@NgModule({
  declarations: [
    AppComponent,
    UserComponentComponent,
    MyComponentComponent
  ]


A component must belong to a NgModule for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule.

Each component in Angular has its own isolated scope. So all the component's dependencies like services, other components, HTML, CSS, and test files are not accessible to any other component outside of its own scope. 

This isolation is important for ensuring modularity and flexibility in an Angular application. In addition to the metadata configuration specified via the Component decorator, components can control their runtime behavior by implementing various Life-Cycle hooks.

Q111. What are Modules in Angular? What are the advantages of modules in Angular?

Modules are larger units that group together one or more related components. It is nothing but a ts file. A module is a place where we can group related components, directives, services, and pipes. It classifies and encapsulates services, components, and directives, into a single cohesive unit. A Module decides whether the components, directives, etc. can be used by other modules, by exporting or hiding these elements.

A module is defined with a @NgModule decorator in Angular. Each and every Angular application has a single root module that acts as the program's entry portal. The main reason why modules are used is to enhance application composability and modularity.

For creating a module: 

ng g module my-module

The above command will generate the "my-module" in the current path.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class MyModuleModule { }

If you notice, it imports the CommonModule by default. 

Advantages of Module:

Encapsulation: A Module helps you to group together related code and things.

Lazy Loading: The application’s performance is enhanced when modules are lazy-loaded only when required. 

Reusability: We can reuse modules across different applications, making it easier to share code between projects.

Dependency Management: The module enhances the dependency management of your application by declaring its dependencies on other modules.

Q112. What is declarable in Angular? Where is it defined in Angular?

Declarable is a class type that you can add to the declarations list of an @NgModule. The class types such as components, directives, and pipes can be declared in the module. You can add classes, components, directives, and pipes to a declarations list.

The structure of declarations would be:

declarations: [
  YourComponent,
  YourPipe,
  YourDirective
]

If you see the app.module.ts file this is the declarations section:

@NgModule({
  declarations: [
    AppComponent,
    UserComponentComponent,
    MyComponentComponent
  ],


However, there are some restrictions as well on declarable classes. Below are things that shouldn't be declared:

  • A class that's already declared in another module or @NgModule
  • An array of directives is imported from another module.
  • Module classes
  • Service classes
  • Helper classes
  • Non-angular classes and objects

Q113. What are the different types of Modules in Angular? 

There are basically two main categories of Angular modules:

  1. Root Module or AppModule
  2. Feature Module

Root Module or AppModule:

Every application can have only one root module whereas it can have one or more feature modules. Every application has at least one Angular module, i.e. the root module that you bootstrap to launch the application. It is known as AppModule.

A root module always imports BrowserModule. The root module is defined inside the app.module.ts file.

Common services are placed in the Core Module to ensure we have only a single instance of the services to avoid unexpected behaviors. 

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Feature Modules:

Feature modules are user-defined modules that you create around specific application business domains, user workflows, and utility collections. They support your application by containing a particular feature, such as routes, services, widgets, etc. In a feature module, all of the content is going to be encapsulated inside of a single area. Feature modules are NgModules for the purpose of organizing code.

If we need to use some common functionality in your Feature Modules you can import the Shared Module in the Modules that needs it. Some of the feature modules are Domain feature modules, Routing feature modules, Service feature modules, etc. 

To create a feature module, run the following command: 

ng g m myfeature-module

The feature module by default imports the CommonModule.

Q114. What is the difference between RootModule vs. FeatureModule in Angular?

RootModule vs FeatureModule:

  1. Every application can have only one root module whereas it can have one or more feature modules. 
  2. The root module is basically an app module which is the entry point of the application and contains bootstraping logic.
  3. A root module imports BrowserModule, whereas a feature module imports CommonModule
  4. The Root module is defined inside the app.module.ts file while the Feature module can be defined in any other user-defined module.ts file. 

Q115. What are BrowserModule and CommonModule in Angular? What is the difference between CommonModule vs. BrowserModule in Angular?

BrowserModule:

The BrowserModule provides services that are essential to launch and run a browser app. BrowserModules are included automatically in the root AppModule when you create a new app with the CLI new command. The root application module i.e. AppModule, always imports BrowserModule so that it can have all the services that are essential to launch and run a browser app.

The BrowserModule is imported from from @angular/platform-browser. BrowserModule also re-exports CommonModule from @angular/common, which means that components in the AppModule module also have access to the Angular directives every app needs, such as NgIf and NgFor. 

That is the reason, it is advised that only the root application module i.e. AppModule, should import BrowserModule and all other feature modules should import CommonModule because we only need the Angular directives in the feature module and not the services that are required to launch the app(Which are already available in RootModule.

CommonModule:

In Angular, the common module that is available in the package @angualr/common is a module that encapsulates all the commonly needed features of Angular, such as services, pipes, directives, etc. 

It also contains some sub-modules such as the HttpClientModule, which is available in the @angular/common/http package. Because of the modular nature of Angular, its functionalities are stored in small self-contained modules, which can be imported and included in our projects if we need these functionalities.

A feature module always imports CommonModule by default. The CommonModule is used to export all the basic Angular directives and pipes such as NgIf, NgForOf, DecimalPipe, and so on. Feature modules mainly import CommonMudule which contains basic directives and pipes such as NgIf, NgClass, and DatePipe.

CommonModule is re-exported by BrowserModule as well. So BrowserModule has the same stuff as CommonModule but also stuff that is used for rendering. To conclude, the BrowserModule should only be imported once, and that too in the root module. For all the other feature modules, it is enough to import the CommonMudule.

CommonModule vs BrowserModule:

CommonModule is basically a subset of BrowserModule. BrowserModule uses the CommonModule itself and also it re-exports CommonModule further. 

For individual import, the BrowserModule can be imported from @angular/platform-browser while CommonModule can be imported from @angular/common

Q116. What will happen if browserModule is used in a Feature Module?

If you do import BrowserModule into a lazy loaded feature module, Angular returns an error telling you to use CommonModule instead. Because BrowserModule’s providers are for the entire app it should only be in the root module, not in the feature module. Whereas Feature modules only need the common directives in CommonModule.

Actually, BrowserModule provides services that are essential to launch and run a browser application, and the root module of the application usually always imports BrowserModule from @angular/platform-browser already. BrowserModule also re-exports CommonModule from @angular/common, which means that components in the AppModule also have access to the Angular directives every application needs.

So do not import BrowserModule in any other module. Feature modules and lazy-loaded modules should import CommonModule instead. They need the common directives. They don't need to re-install the app-wide providers.

Q117. What will happen if you import the same module twice in Angular? How can you avoid circular module dependency in Angular?

If multiple modules import the same module then angular evaluates it only once when it encounters that module the very first time. It follows this condition even if the module appears at any level in a hierarchy of imported NgModules.

When two imported modules, loaded at the same time, list a provider with the same token, the second module's provider "wins". That's because both providers are added to the same injector. When Angular looks to inject a service for that token, it creates and delivers the instance created by the second provider.

Every class that injects this service gets the instance created by the second provider. Even classes declared within the first module get the instance created by the second provider.

If NgModule A provides a service for token 'X' and imports a NgModule B that also provides a service for token 'X', then NgModule A's service definition "wins".

However, the service provided by the root AppModule takes precedence over services provided by imported NgModules. So the AppModule always wins.

Circular Dependency in Angular:

It is not a problem when three modules X, Y, and Z all import module 'A'. Angular evaluates module 'A' once, the first time it encounters it, and doesn't do so again. That's true at whatever level A appears in a hierarchy of imported NgModules.

But Angular does not allow NgModules with circular references, so don't let Module 'A' import Module 'B', which imports Module 'A'.

A Circular Dependency is when one of your modules imports another module, which directly or via other modules imports the first module. For example:

Direct reference: A -> B -> A
Indirect reference: A -> B -> C -> A

Not all circular dependencies cause issues. However, you might have seen this quite vague exception message. There are several tools that allow finding circular dependencies like Madge.

Q118. What is the difference between Component vs. Module in Angular?

  1. A component is a class that has an associated template that defines a view. However, a module is a container for a set of related components and directives.
  2. A component is basically responsible for rendering a view and handling user interactions with the view. On the other hand, a module can contain services, pipes, and other code that is used by the components that are a part of the module.
  3. A component is defined using @Component decorator while a module is defined using @NgModule decorator.
  4. A component controls only a part of the screen called a view.  While a module provides a way to group related functionality and keep the code organized and maintained.
  5. A component can interact with other components or services while a module can contain multiple components and directives.

Q119. What is the difference between Component vs. Directive in Angular?

  1. To register components, we use @Component decorator while for directives we use @Directive decorator. 
  2. A component is used to create a new View(Shadow DOM) with attached behavior while a Directive is used to add behavior to an existing DOM element. Many directives can be used in a per DOM element
  3. With the help of Component, we can break our application into smaller components and can do component-based development while with the help of Directive, we can attach different behaviors to an existing DOM element or different existing DOM element.
  4. Component is used to create reusable components while Directive is used to create reusable behaviour.
  5. A view or templates are the mandatory property and always required in the Component. However, a directive doesn’t always require any view or templates.
  6. A Component is always an element while a directive can be an attribute, element name, comment, or CSS class.
  7. A component use viewEncapsulation as it contains the view. You can not use viewEncapsulation in the directive as it does not contain any view.
  8. Only one component can be present per DOM element but there can be more than one directive in a DOM element.

Q120. What is the difference between NgModule vs. JavaScript Module?

In an Angular app, both NgModules and JavaScript modules work together.

JavaScript Module:


Before ES6 (ES2015), there was no module system in the standard of the ECMAScript language. What we had instead, were different implementation patterns for “simulating” a module system: there are the simple IIFEs (Immediately Invoked Function Expression), UMD (Universal Module Definition), AMD (Asynchronous Module Definition), and CommonJS. As of ES6, JavaScript also supports a native module format. It uses an export token to export a module's public API.

A JavaScript module is an individual file with JavaScript code, usually containing a class or a library of functions for a specific purpose within your application. JavaScript modules let you spread your work across multiple files.

In modern JavaScript, every file is a module. Within each file, you write an export statement to make parts of the module public. In JavaScript, modules are individual files with JavaScript code in them. To make the code in a JavaScript module available to other modules, use an export statement at the end of the relevant code in the module. 

export class AppComponent { ... }

Then, when you need that file's code in another file, you import it like this:

import { AppComponent } from './app.component';

JavaScript modules help us to namespace, preventing accidental global variables. Each module has its own top-level scope. In other words, top-level variables and functions in a module are not seen in other scripts or modules. Each module provides a namespace for identifiers to prevent them from clashing with identifiers in other modules. With multiple modules, you can prevent accidental global variables by creating a single global namespace and adding submodules to it.

Angular NgModules:

The NgModules are classes decorated with @NgModule. NgModules are specific to Angular. While classes with an @NgModule decorator are by convention kept in their own files, they differ from JavaScript modules because they include this metadata.

The @NgModule decorator’s imports array tells Angular what other NgModules the current module needs. The modules in the imports array are different than JavaScript modules because they are NgModules rather than regular JavaScript modules.

Angular's NgModule has imports and exports and they serve a similar purpose. You can import other NgModules so you can use their exported classes in component templates. You export this NgModule's classes so they can be imported and used by components of other NgModules.

NgModules vs JavaScript Modules:

  1. An Angular NgModule is a class with the @NgModule decorator while JavaScript modules do not have any decorator.
  2. NgModule bounds declarable classes only while in the JavaScript module there are no restriction classes.
  3. NgModule lists the module's classes in declarations array only but in the JavaScript module, we can define all member classes in one giant file.
  4. NgModule only exports the declarable classes it owns or imports from other modules but a JavaScript module can export any classes.
  5. NgModule extends the entire application with services by adding providers to the provides array but a JavaScript module can't extend the application with services.

Q121. How does Angular find components, directives, and pipes in a template? What is a template reference?

The Angular compiler looks inside component templates for other components, directives, and pipes. Angular compiler finds a component or directive in a template when it can match the selector of that component or directive to some HTML in that template. When it finds one, that's a template reference.

The compiler finds a pipe if the pipe's name appears within the pipe syntax of the template HTML. Angular only matches selectors and pipe names for classes that are declared by this module or exported by a module that this module imports.



Recommended Articles




Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.