Tech Point Fundamentals

Saturday, December 9, 2023

Angular Interview Questions and Answers - Part 12

Angular Interview Questions and Answers - Part 12

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 12th 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:

Q136. What is data binding in Angular? Which type of data binding does Angular use?
Q137. What are the different types of data binding used in Angular?
Q138. What is Property Binding in Angular? What is the use of [] or square box in Angular?
Q139. What is Attribute Binding in Angular? What is the difference between Property Binding vs Attribute Binding in Angular?
Q140. What is the difference between colspan vs. colSpan (camel case) in Angular?
Q141. What is String Interpolation in Angular?
Q142. What is Event Binding in Angular? What is the use of $event payload in Angular?
Q143. What is a Template Reference Variable in Angular?
Q144. What is the difference between Property Binding vs. Event Binding?
Q145. Can you use angular interpolation in the place of property binding?
Q146. What is two-way data binding in Angular? What are the disadvantages of two-way data binding?
Q147. What is the difference between (change) vs. (ngModelChange) events in Angular?
Q148. What is the difference between [ngModel] vs. [(ngModel)] in Angular?

Angular Interview Questions and Answers: Part 12


Q136. What is data binding in Angular? Which type of data binding does Angular use?

In Angular, data binding refers to the mechanism of establishing a connection between the component’s data i.e. model, and the user interface i.e. view elements. It allows the automatic synchronization and communication of data between the component and the template. 

Data binding provides a way to keep the data in the component and the UI in sync, ensuring that any changes made to the data are reflected in the view, and vice versa. 

We use data binding in web pages that contain interactive components such as forms, calculations, and cascading reflections of change. Incremental display of a webpage makes data binding convenient when pages have an enormous amount of data.

Angular uses two types of data binding: one-way data binding and two-way data binding.

Q137. What are the different types of data binding used in Angular?

There are basically two broad categories in which we can divide the data bindings in Angular:

1. One-Way Data Binding (Uni-Directional Data Flow):

In Angular One-way data binding is a way to bind data from the component to the view (DOM) or vice versa i.e. from the view to the component. It is used to display information to the end-user which automatically stays synchronized with each change of the underlying data. 

A. From Component to View: (Model ==> View)

  1. Property Binding
  2. Interpolation

B. From View to Component: (View ==> Model)

  1. Event Binding

2. Two-Way Data Binding (Bi-Directional Data Flow):

In two-way data binding any changes made to the model in the component are propagated to the view and any changes made in the view are immediately updated in the underlying component data. The two-way data binding is nothing but both property binding & event binding applied together.

Q138. What is Property Binding in Angular? What is the use of [] or square box in Angular?

Property Binding is a technique to achieve one-way data communication or binding in Angular. It helps you to set values for properties of HTML elements or directives in Angular. Property binding moves a value in one direction, from a component's property into a target element property.

Property binding in Angular is used to bind values for target properties of HTML elements or directives. A target property is the DOM property to which you want to assign a value. 

To bind to an element's property, enclose it in square brackets i.e. [], which identifies the property as a target property. So in property binding, the property name is wrapped into square brackets, and its value does not contain curly braces - just the name of the property that it is bound to. 

<input type="text" [disabled]="isDisabled">

Here by using property binding, the input textbox's disabled property is bound to a boolean result, not a string. The isDisabled value is false and running the app would display the input as enabled.

In most cases, the target name is the name of a property, even when it appears to be the name of an attribute. For example, src is the name of the <img> element property.

<img alt="item" [src]="itemImageUrl">

Tech Points:

1. The square brackets i.e. [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value

2. It is very important to remember that when a binding relies on the data type result, then always a property binding should be used. If the binding simply relies on a string value, then interpolation should be used.

For example, when the "isDisabled" flag is set to true then all the below text boxes will be in disabled mode:

<input id="textbox-1" type="text" [disabled]="isDisabled"/>
<input id="textbox-2"  type="text" disabled="{{isDisabled}}"/>
<input id="textbox-3"  type="text" disabled="isDisabled"/>

If you check the HTML source code for the above Angular code is:

property-binding

But when the "isDisabled" flag is set to false only the first textbox will be enabled and rest two will be in disabled mode:

property-binding-2

So the conclusion is if you are not using the square bracket [] you can not even use string interpolation as well.

Q139. What is Attribute Binding in Angular? What is the difference between Property Binding vs Attribute Binding in Angular?

Both Interpolation and Property Binding are dealing with the DOM Properties but not with the HTML attributes. But some HTML elements like colspan, area, etc. do not have the DOM Properties. So you can not either use either interpolation or property binding with them.

With Attribute Binding in Angular, you can set the value of an HTML Element Attribute directly. So, Attribute Binding is used to bind the attribute of an element with the properties of a component dynamically. 

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.

Property Binding vs Attribute Binding:

Attribute Binding syntax resembles Property Binding because both use a square box i.e. [], but instead of an element property between brackets, you precede the name of the attribute with the prefix attr, followed by a dot. Then, you set the attribute value with an expression that resolves to a string. When the expression resolves to null or undefined, Angular removes the attribute altogether.

One of the primary use cases for attribute binding is to set ARIA attributes. The second common use case for attribute binding is with the colspan attribute in tables. Binding to the colspan attribute helps you to keep your tables programmatically dynamic. 

<button type="button" [attr.aria-label]="actionName">{{actionName}} with Aria</button>
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>

Here the colspan binding causes the <tr> to span two columns.

Q140. What is the difference between colspan vs. colSpan (camel case) in Angular?

A common point of confusion is between the attribute colspan and the property colSpan. Actually, colspan is not a property of td element instead colspan is an attribute. Notice that these two names differ by only a single letter.

Sometimes there are differences between the name of the property and an attribute. The colspan is an attribute of <td>, while colSpan with a capital "S" is a property of <td>. When using attribute binding, use colspan with a lowercase "s".

To use attribute binding using colspan, type [attr.colspan] while using property binding using colSpan type [colSpan]:

<tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
<tr><td [colSpan]="1 + 1">Three-Four</td></tr>

Q141. What is String Interpolation in Angular?

String Interpolation is a One-way Data-Binding technique that is used to transfer the data from a TypeScript model code to an HTML template (view).  It outputs the data from TypeScript code to HTML view.

Interpolation refers to embedding expressions into marked-up text directly. By default, interpolation uses the Double Curly Braces {{  }} as delimiters. It is also known as the mustache syntax. It is a special syntax that makes use of double curly braces {{}} so that it can display the component data. 

We use our template expression within the double curly braces to display the data from the component to the view. Inside the braces are the JavaScript expressions that Angular needs to execute to retrieve the result, which can further be inserted into the HTML code. 

<div>{{ userName }}</div>
<div>{{ "Role Name: " + userRole.toUpperCase() }}</div>
<div> Role Name: {{  userRole.toUpperCase() }}</div>
<div>{{ user.Email }}</div>
<div>{{ getUserAddress() }}</div>
<div>{{ :Gender : " +items[0] }}</div>
<div>{{ 2 + 2 }}</div>

You can bind object property, field, method name, any mathematical expression, pipe, and so on. So you can do and use all the Javascript expressions in {{}}.

Tech Points:

Although the interpolation looks quite powerful, it has its limitations as well. It only represents a string. So whatever things are projected or inserted/returned by interpolation {{}} is always a string. That's why the name is String Interpolation.

<input type="text" disabled="{{ isDisabled }}">

Here the expected result should be that the input should be enabled, but it's disabled. This is because the interpolation returns a string, but the input's disabled property is of boolean type and it requires a boolean value. To work correctly for this,  you need to use property binding.

Q142. What is Event Binding in Angular? What is the use of $event payload in Angular?

Event Binding is a one-way data binding i.e. from view to component in Angular. By tracking the user events in the view and responding to it, we can keep our component in sync with the view.  It allows us to bind JavaScript events to an HTML element.

Event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When any DOM event happens at an element, it calls the specified method in the particular component. Using Event Binding we can bind data from DOM to the component and hence can use that data for further purposes.

To determine an event target, Angular checks if the name of the target event matches an event property of a known directive. An event handler can simply be considered as a method or function that handles the event of a specific HTML element.

To bind to an event you use the Angular event binding syntax. Angular event binding syntax consists of a target event name within parentheses on the left of an equal sign and a quoted template statement on the right.

<button (click)="showMessage()">Show Message</button>

Instead of parentheses, you can also use the on-syntax as shown below.

<button on-click="showMessage()">Show Message On Click</button>

You can also bind an unlimited number of event handlers on the same event by separating them with a semicolon(;).

$event Payload:

Angular DOM Events carry the event payload information. We can access the event payload by using the $event as an argument to the handler function. DOM events have useful information about the user event in the $event payload. The properties/information/context of a $event object vary depending on the type of DOM event. If the target event is a native DOM element event, then it is an object.

<button (click)="onShow($event)">Show Event</button>

Remember you need to use the variable as $event in the Template statement. Otherwise, it will result in an error.

Q143. What is a Template Reference Variable in Angular?

Components have a template property in Angular, that holds HTML elements and other components. The template reference variable is a reference to any DOM element, component, or directive in the Template.

A template reference variable often references to a DOM element within a template.  A template reference variable is a feature that allows us to gain access to a part of our template. This could be an element, component, or could be a directive. We can use it elsewhere in the template. We can also pass it to a method in the component.

This reference variable can be a reference to an Angular component, directive, or web component. That means you can easily access the variable anywhere in the template. Usually, the reference variable can only be accessed inside the template. However, you can use ViewChild decorator to reference it inside your component as well.

You declare a reference variable by using the hash symbol(#) followed by the name of the variable. We can also declare them using #variable="user" when the component/directive defines a "user" as the exportAs Property. Template variables help you use data from one part of a template in another part of the template.

Angular assigns a value to the template variable based on the context. If we declare in an HTML tag, the value refers to that HTML element. If we declare it in a component, the value refers to the component instance. The Template statement can change the state of the component. Angular runs the change detection and updates the view to keep it in sync with the component.

<input type="text" #name>
<button (click)="show(name)">Show Name</button>

Now you can define the show() in the component. But remember as I said it often references to DOM  element, so here it refers to the HTMLInputElement type.  

show(name: HTMLInputElement){
    console.log(name.value);
    alert(name.value);
};

Here you can think of this syntax (#name) as an “export”. We are exporting a reference to the element (DOM). That means that we can now access properties on that reference variable as if it were returned to us through plain JavaScript.

In the above example #name variable is directly giving us an HTMLInputElement. For us to see the value as we type, we would need to introduce the ngModel Directive:

<input type="text" ngModel #name>
<p>{{ name.value }}</p>

Now you will be able to see immediately whatever the user has typed. 

Actually by only specifying the #name we are implicitly letting Angular decide what to export because we are not specifying anything other than binding to the element, that is why Angular has exported the DOM element type.

But by passing #name="ngModel" we are explicitly binding a reference to our tracked ngModel directive. No longer do we have an HTMLInputElement. We have a reference to NgControl explicitly. Now it shows you every property available to you, which is exactly why we’ve referenced not only value but pristine and touched as well.

<input type="text" ngModel #name="ngModel">
<p>{{ name.value }}</p><br>
<p>Pristine: {{ name.pristine }}</p><br>
<p>Touched:  {{ name.touched }}</p>

But now the show() method of the component will break as the template reference variable is no more referencing to HTMLInputElement.

Q144. What is the difference between Property Binding vs Event Binding?

Both property and event binding are used as one-way data binding in Angular. But Property Binding is used when we want to send data (either static or dynamic) from component to view  (parent to the child component) and Event Binding is used to fire an event (on-click, keyup, any custom event) from view to component (child component which can be caught by parent component). 

Property Binding means we pass the data from the component class and set the value to the given element in the View. This is one way where the data is passed from the component to View. On the other hand Event binding is the one-way data binding that sends the value from the view to the component which is in contrast to the property binding where we used to send the data from the component to the view.

There are three ways by which we can achieve the property binding: 
  •      Interpolation 
  • By using Square [] brackets
  • By using the “bind- “prefix before the element property. 

On the other hand, there is two way to achieve event binding:
  • By wrapping the event in parentheses () and assigning the method from the component
  • By appending "on-" before the event and assigning the method from the component

Q145. Can you use angular interpolation in place of property binding?

Yes, you can use angular interpolation instead of property binding but there are some limitations with angular interpolation. Interpolation only works with the string values. If anything requires some other data type result like a boolean, you can not use interpolation.

Suppose a button and you want to disable and enable the button based on some condition. To disable a button we have disabled property and we can not set string value to the disabled property, it only works with a boolean. In such a case, we need to use property binding.

Q146. What is two-way data binding in Angular? What are the disadvantages of two-way data binding?

Two-way data binding in Angular is a feature that enables automatic data synchronization between the view and the model. The View and application state changes will be mirrored automatically. It allows data to flow in both directions between the component class and the template. 

This implies that any changes made to the view (user interface) are mirrored instantly in the underlying model (data source), and vice versa. If you alter data in one area, it will immediately reflate at the other end. This happens instantly and automatically, ensuring that the HTML template and TypeScript code are always up to date. 

Banana-Box Syntax:

Actually, a two-way data binding performs the following two actions: 
  1. Sets a property of a component class i.e. ()
  2. Listens for a DOM element change event that may change that property i.e. []

So we can achieve two-way data binding in Angular via a combination of property binding and event binding. It uses banana box [()] syntax. 

Angular's two-way binding syntax is a combination of square brackets and parentheses i.e. [()]. Angular's two-way binding syntax is a combination of square brackets and parentheses i.e. [()]. The two-way binding syntax combines the brackets of property binding i.e. [], with the parentheses of event binding i.e. ().

ngModel Directive:  [ngModel] vs [(ngModel)]

Angular 2+ supports inbuilt two-way data binding using ngModel directive. The [(ngModel)] syntax is the recommended way of two-way data binding. The ngModel directive with only [] syntax i.e. [ngModel] is used for one-way data binding that binds a value to a property to UI control. While [(ngModel)] is used for two-way data binding.

The ngModel directive with [()] syntax syncs values from the UI to a property and vice-versa. So, whenever the user changes the value on the UI, the corresponding property value will get automatically updated.

<div>
Name: <input type="text" placeholder="Type you name here" [(ngModel)]="Name" >
Typed Name: {{Name}}
</div>

Actually [(ngModel)]="Name" is  is just a short-hand that can be de-sugared to:

<input type="text" placeholder="Type you name here" [ngModel]="Name" (ngModelChange)="Name = $event">
<p> {{Name}} </p>

Disadvantages of Two-Way Data Binding:

Two-way data binding has been supported in Angular for a long time. However, it is something that should be used with careful consideration as it could lead to poor application performance or performance degradation as time goes on. 

It is called two-way data binding because we can change some data that is in the component model from the view that is HTML, and that change can also propagate to all other places in the view where it is displayed.

Q147. What is the difference between (change) vs. (ngModelChange) events in Angular?

The "change" is not an Angular event, it is a DOM event. Whereas ngModelChange is an Angular event that fires when ngModel changes.

(change) Event:

The change event is fired for HTML control like <input>, <select>, and <textarea> elements when an alteration to the element’s value is done by the user. The change event is not necessarily fired for each alteration to an element’s value. 

A (change) event is a DOM event that is it can trigger changes in HTML tags and elements. A (change) event bound to classical input change event only. You can use (change) event even if you don't have a model at your input element.

<input type="text" (change)="somethingChanged()">

Here the (change) binding is listening for a DOM event called change, which will give us exactly what we’d expect in “plain JavaScript DOM” outside of the Angular system. Our somethingChanged() would then be given the regular Event object.

(ngModelChange) Event:

When the user wants to change the model, by entering text into the input, the event callback fires and sets the new value to the model. ngModelChange will only be fired when the model changes or updates. The (ngModelChange) will only fire when the model is intended to be updated.

Actually, the (ngModelChange) is the @Output of ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive.

The NgModel class has the update property with an EventEmitter instance bound to it. We can not use ngModelChange without ngModel because the ngModel class has an update function with the EventEmitter instance. 

<input type="text" [ngModel]="Name" (ngModelChange)="Name = $event">
<p> {{Name}} </p>

If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds the previous value. If you place it after ngModel, the model will already have the new value.

<input type="text" (ngModelChange)="onModelChange()" [ngModel]="Name" (ngModelChange)="Name = $event" >

When the user wants to change the model, by entering text into the input, the event callback fires and sets the new value to the model.

(change) vs (ngModelChange):

The (change) event is bound to the HTML on the change event, which is a DOM event. On the other hand, ngModelChange is bound to the model variable bound to your input, which is an Angular event.

The (change) event is bound to the classical input change event while ngModelChange fires when the model changes. 

The (change) event triggers when the user changes the input. While the (ngModelChange) triggers when the model changes, irrespective of whether that change is caused by the user or not.

We can’t use (ngModelChange) without ngModel,  whereas the (change) event can be used anywhere.

Using (change) event will only fire when the user has blurred the input. But using (ngModelChange) essentially is listening to the input event, and setting the model if a user types, pastes, or changes the input’s value.

In Angular 7 and more the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed. On the other hand the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

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

The ngModel directive with only [] syntax i.e. [ngModel] is used for one-way data binding (event binding) that binds a value to a property into the UI control. While [(ngModel)] is used for two-way data binding. Angular 2+ supports two-way data binding using the [(ngModel)] directive. 

<input type="text" placeholder="Type you name here" [(ngModel)]="Name" >
<p> {{Name}} </p>

Actually [(ngModel)]="Name" is just a short-hand of following:

<input type="text" placeholder="Type you name here" [ngModel]="Name" (ngModelChange)="Name = $event">
<p> {{Name}} </p>



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.