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.

No comments:

Post a Comment

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