Tech Point Fundamentals

Saturday, December 2, 2023

Angular Interview Questions and Answers - Part 11

Angular Interview Questions and Answers - Part 11

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 common as frontend technology so it is very important 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 11th 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 & Answers and important technology videos.

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

Q122. What are Directives in Angular? When to use directive?
Q123. What are the different types of directives in Angular?
Q124. What is the use of the *ngFor directive? What is the difference between the *ngFor vs. ngForOf directive in Angular?
Q125. What is the index property in *ngFor directive? What is the use of index property in *ngFor directive?
Q126. What is the purpose of *ngFor trackBy in Angular?
Q127. What is the use of the *ngIf directive in Angular? 
Q128. What is the difference between the *ngIfElse vs. *ngIf directive in SQL?
Q129. How can you use both *ngFor and *ngIf directives together on the same element?
Q130. What is the difference between the *ngIf directive vs. hidden property in Angular?
Q131. What is the use of the *ngSwitch directive?
Q132. What is the difference between the *ngStyle vs. *ngClass directive in Angular?
Q133. What is the use of ng-template in Angular?
Q134. What is the use of the ngModel directive in Angular? What is the "banana-in-a-box" syntax in Angular? 
Q135. What is the difference between the (ngModel) vs [ngModel] vs [(ngModel)] directive in Angular?

Angular Interview Questions and Answers: Part 11


Q122. What are Directives in Angular? When to use directive?

A directive is used to extend the syntax and capabilities of a normal HTML view in Angular. It has a very special syntax and meaning which are understood by Angular compiler only. When Angular begins compiling the TypeScript, CSS, and HTML files into a single JavaScript file, it scans through the entire code and looks for a directive that has been registered. In case it finds a match, then the compiler changes the HTML view accordingly.

A directive is a class that is declared with a @Directive decorator. A Directive adds custom behavior to elements and components. They enable developers to create reusable components that can be utilized across different parts of an application. Every directive has its own behavior and can be imported into various components of an application.

Q123. What are the different types of directives in Angular?

Angular is shipped with many built-in directives. However, we can build our custom directives and let Angular know what they do so that the compiler knows about them and uses them during the compilation process. 

In Angular, there are three main built-in categories of directives: Component Directive, Attribute Directive, and Structural Directive.

1. Component Directives: 

A component is simply a directive with a template. It is used to define a single piece of the user interface using TypeScript code, CSS styles, and the HTML template. These are directives that define new custom elements, which can be used as UI components in an Angular application.

These form the main class in directives. Instead of @Directive decorator, we use @Component decorator to declare these directives. These directives have a view, a stylesheet, and a selector property.

Components can be used as directives. Every component has an Input and Output option to pass between the component and its parent HTML elements.

<list-item [items]="fruits"> ... </list-item>

Here, the list item is a component and items are the input option.


2. Attribute Directives: 

Attribute directives change the appearance or behavior of a DOM element, component, or another directive.  They are used as the attributes of elements. The following are the common Attribute directives in Angular:

  1. NgStyle Directive
  2. NgClass Directive
  3. NgModel Directive

3. Structural Directives: 

Structural directives are used to change the structure of the DOM or view by adding or removing the elements. These directives are called structural directives because they change the structure of the template. 

These directives are generally used to manipulate DOM elements. Every structural directive is denoted by a * sign before them. We can apply these directives to any DOM element. These are directives that change the template's structure by adding, removing, or modifying DOM elements.

  1. NgIf Directive
  2. NgIfElse Directive
  3. NgFor Directive
  4. NgSwitch Directive

Q124. What is the use of the *ngFor directive? What is the difference between the *ngFor vs. ngForOf directive in Angular?

The *ngFor is a commonly used shorthand form for the ngForOf directive in Angular. The ngFor is a structural directive. It is basically used to display lists, tables, or any other structured data where repetitive rendering is required. It is used in the template to display each item in the list.

The purpose of the "ngFor" directive in Angular is to iterate over a collection or an array and generate repetitive HTML elements or components based on each item in the collection. It allows for dynamic rendering of content by repeating a template block for each item in the specified collection.

<div class="details" *ngFor="let x of details" >
<p>{{x.name}}</p>
<p> {{x.address}}</p>
<p>{{x.age}}</p>
</div>

Difference between *ngFor vs ngForOf Directive:

The *ngFor and ngForOf are not two distinct things. The *ngFor is a shorthand for ngForOf. They are actually the selectors of the NgForOf directive. Both attributes need to be present on an element for the directive to 'activate'.

The ngFor attribute is just a marker, while the ngForOf attribute is actually an input to the directive that points to the list of things you want to iterate over.

One main difference between them is that [ngFor] is not type-safe while [NgForOf] is type-safe. Because ngFor Class type is any type while ngForOf class type is generic ngForOf NgIterable<T>.

<div *ngFor="let item of items"></div>

When you use *ngFor, the Angular compiler de-sugars that syntax into its canonical form which has both attributes on the element. This first de-sugaring is due to the '*'. 

<template [ngFor]="let item of items">
    <div>...</div>
</template>

Now the next de-sugaring is because of the micro syntax: "let item of items". The Angular compiler de-sugars that as well into the following:

<template ngFor let-item="$implicit" [ngForOf]="items">
    <div>...</div>
</template>

Here $implicit is an internal variable that the directive uses to refer to the current item in the iteration. 


Q125. What is the index property in *ngFor directive? What is the use of index property in *ngFor directive?

The index property of the NgFor directive is used to return the zero-based index of the item in each iteration. You can capture the index in a template input variable and use it in the template. 

Actually, each iteration inside the NgFor loop exposes to us a set of local variables: index, count, first, last, even, and odd. You can declare a variable inside *ngFor directive using let or as a keyword and just assign the variable value to the index.

So if you want to access the index like we could inside a typical Array.prototype.forEach, we can use the following syntax to expose the index variable:

<ul>
    <li *ngFor="let book of books; let i = index;">
      Index: {{i}} value : {{book.name}}
    </li>
</ul>

By declaring the index as i we make the index value available to us under a variable called i. From here, we can then use {{ i }} inside the template to log out the value for each item in the loop.

Q126. What is the purpose of *ngFor trackBy in Angular?

The main purpose of using *ngFor with the trackBy option is performance optimization. Sometimes, ngFor performance is low with large lists. To iterate over large objects collection, we use trackBy. It is used to track when elements are added or removed. 

Normally if you use NgFor with large data sets, a small change to one item by removing or adding an item, can trigger a cascade of DOM manipulations. In this case, Angular sees only a fresh list of new object references and replaces the old DOM elements with all new DOM elements.

You can help Angular to track which items are added or removed by providing a trackBy function which takes the index and the current item as arguments and needs to return the unique identifier for this item. It is performed by trackBy method. It has two arguments index and element. An index is used to identify each element uniquely.

<ul>
    <li *ngFor="let std of studentArr; trackBy: trackByData">
       {{std.name}}
    </li>
 </ul>

Now you need to define the trackByTodos method in any student.component.ts file:

export class TestComponent {
  studentArr: any[] = [ { "id": 1, "name": "student1" }, { "id": 2, "name": "student2" }]
   
  trackByData(index:number, studentArr:any): number {
   return studentArr.id;
  }
}

Q127. What is the use of the *ngIf directive in Angular?

The *ngIf directive is used to display or hide data in the application based on the specific condition that becomes true or false. We can add this to any tag in the template. 

Also, the ngIf directive is to remove or recreate a part of the DOM tree in alignment with an expression. If the ngIf directive finds the expression being evaluated to be false, the element is removed from the tree, else a matching element is inserted into the DOM tree.

<p *ngIf="user.age > 18">You are not eligible to create any account !</p>

If you set the condition ngIf="false" then, the contents will be hidden. Here, actually, Angular is not showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in larger projects with many data bindings.

Q128. What is the difference between the *ngIfElse vs. *ngIf directive in SQL?

The *ngIfElse is similar to ngIf except, it provides an option to render content during failure scenario as well in the else part.

First, let's write the logic in the ts file:

export class UserComponent implements OnInit {
  isLogIn :  boolean = false;
  isLogOut : boolean = true;
}

Now let's use the ngIfElse logic in the HTML file:

<div *ngIf="isLogIn; else isLogOut">
    Welcome to the portal!
 </div>
 <ng-template #isLogOut>
    You're logged out successfully
 </ng-template>

Q129. How can you use both *ngFor and *ngIf directives together on the same element?

Sometimes we may need to use both ngFor and ngIf on the same element. Unfortunately, if you do that, you are going to get a template parse error if you use both together.

<ul *ngIf="items" *ngFor="let item of items">
    <li>{{item}}</li>
</ul>

The compiler will throw the below error if you use the above code:

error NG5002: Can't have multiple template bindings on one element. Use only one attribute prefixed with *

In this case, You need to use either ng-container or ng-template:

<ng-container *ngIf="items">
    <ul *ngFor="let item of items">
      <li>{{item}}</li>
    </ul>
</ng-container>

Q130. What is the difference between the *ngIf directive vs. hidden property in Angular?

Both are ways to show or hide an element in Angular. The only difference between them is that: *ngIf removes the element from the DOM while [hidden] tells the browser to show or hide an element using the CSS display property by keeping the element in the DOM. So the [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

The hidden property is used to show or hide the associated DOM element, based on an expression. The [hidden] is adding conditionally an attribute "hidden" to the element.  It can be compared closely to the ng-show directive in AngularJS.

Both *ngIf and [hidden] are fundamentally different. The *ngIf will not evaluate the content inside the *ngIf block until the condition is true. If a component is using ngIf and the result is false it will not be rendered at all, so any code inside the component will not run until the ngIf condition is met.

One more thing to take into consideration is that *ngIf destroys the component and it has to be re-created, while [hidden] keeps it alive and in memory. If you have a resource-intense component it may be preferable to hide it instead of destroy it. Generally, it is expensive to add and remove stuff from the DOM for frequent actions.

However, you can also use the ngStyle directive and visibility property as well to hide and show any element.

<div [hidden]="!isTrue">Element is hidden by: Hidden Property</div>
<div *ngIf="isTrue">Element is hidden by: ngIf Directive</div>
<div [style.visibility]="isTrue ? 'visible' : 'hidden'">Element is hidden by: Visibility Property</div>
<div [ngStyle]="{'visibility': isTrue ? 'visible' : 'hidden'}">Element is hidden by: ngStyle Directive</div>

Q131. What is the use of the *ngSwitch directive?

The ngSwitch directive is similar to the JavaScript switch statement which displays one element from among several possible elements, based on a switch condition. NgSwitch is used to check multiple conditions and keep the DOM structure simple and easy to understand. In this case, only the selected element is placed into the DOM.

It is used along with *ngSwitch, *ngSwitchCase, and *ngSwitchDefault directives.

<ul [ngSwitch]="userRole">
    <li *ngSwitchCase="'superAdmin'">
       <p>Super Admin Dashboard</p>
    </li>
    <li *ngSwitchCase="'admin'">
       <p>Admin Dashboard</p>
    </li>
    <li *ngSwitchDefault>
       <p>Annonymous User Dashboard</p>
    </li>
 </ul>

Q132. What is the difference between the *ngStyle vs. *ngClass directive in Angular?

Both are attribute directives in Angular. They perform the appearance or behavior of DOM elements or components. 

The *ngStyle directive is used to add dynamic styles on any element. On the other hand, the *ngClass directive is used to add or remove CSS classes in HTML elements.

 <p [ngStyle]="{'color': 'red', 'font-size': '14px'}">
    Paragraph style is applied using ngStyle
 </p>

 <div [ngClass]="'highlight'">
   Div style is based on ngClass
 </div>

If you want to apply conditional class then you can do that as well:

 <div class="container">
    <br/>
    <div *ngFor="let user of items" [ngClass]="{
       'highlight':user === 'Alex'
    }">
       {{ user }}
    </div>
 </div>

Q133. What is the use of ng-template in Angular?

In angular the ng-template is used to create dynamic and reusable templates. It is a virtual element. If you compile your code with ng-template then is converted as a comment in DOM and nothing will be displayed in the HTML source code.

 <h3>ng-template</h3>
 <ng-template> ng-template Content</ng-template>

If you run the above code, then it will print only the h3 element, not the ng-template element. If you check your page source, the template is displayed in the comment section because it is a virtual element so it does not render anything. We need to use ng-template along with Angular directives.

Normally, a directive emits the HTML tag it is associated with. Sometimes, we don’t want the tag but only the content. We can use ng-template to safely skip the li tag.

<li *ngFor="let item in list">{{ item }}</li>

The ng-template should always be used inside ngIf, ngFor, or ngSwitch directives to render the result.

<ng-template [ngIf]=true>
    <div>ng-template Content</div>
</ng-template>

Q134. What is the use of the ngModel directive in Angular? What is the "banana-in-a-box" syntax in Angular? 

The NgModel is an attribute directive in Angular. The Angular uses the ngModel directive to achieve the two-way binding on HTML Form elements. It is basically used to connect the "view" to the "model". The ngmodel directive binds the value of HTML controls (input, select, textarea) to application data. 

With the ng-model directive, you can bind the value of any input field to a variable created in Angular. The binding can go both ways, which means if the user changes the value inside the input field, the Angular property will also change its value.

The ngModel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package from the @angular/forms library into your Angular module.

<input [(ngModel)]="userRole"><br>
<strong>{{userRole}}</strong><br>
<input type="text " value="{{userRole}}">


"Banana-in-a-Box" Syntax: Two-Way Data Binding

The two-way data binding is nothing but both property binding and event binding applied together. The above syntax sets up both property & event binding. The square indicates the Property binding [ ] & parentheses indicate the event binding ( ). This two-way binding with [()] syntax is also known as "banana-in-a-box syntax". 

Property Binding is one way from view to component while the event binding is one way from component to view. The value that is declared for ngModel is displayed using string interpolation{{ }}.

Q135. What is the difference between the (ngModel) vs [ngModel] vs [(ngModel)] directive in Angular?

  1. The (ngModel) causes a one-way data-binding i.e. event binding from view to component only.
  2. And the [ngModel] causes a one-way data-binding i.e. property binding from component to view only. The Code is evaluated, and an output is generated by [ngModel].
  3. Whereas the [(ngModel)] ensures a two-way data binding i.e. both event binding from view to component and property binding from component to view. So 

<input id="txt1" type="text"  name="userRole" (ngModel) ="userRole"> <br>
<input id="txt2" type="text"  name="userRole" [ngModel] ="userRole"> <br>
<input id="txt3" type="text"  name="userRole" [(ngModel)] ="userRole"> <br>

Here the value changed in the third textbox will be displayed in the second textbox as well. 



Recommended Articles




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

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.