Saturday, 9 January 2021

Angular4 Interview Questions and Answers

 1. What is Angular 4 ?

Angular is an open-source web development framework developed and maintained by Google. It combines declarative templates, end-to-end tooling, dependency injection and integrated best practices to solve development challenges. It is constantly updated for easier usability and increased developer productivity.

2. In how many ways the Data Binding can be done?

Data Binding happens between the HTML (template) and typescript (component). Data binding can be done in 3 ways:

(i) Property Binding (ii) Event Binding (iii) Two-Way Data Binding. 

3. What is the sequence of Angular Lifecycle Hooks?

OnChange()  -  OnInit()  -  DoCheck()  -  AfterContentInit()  -  AfterContentChecked()  -  AfterViewInit()  -  AfterViewChecked()  -  OnDestroy(). 

4. What does a Subscribe method do in Angular 4? 

It is a method which is subscribed to an observable. Whenever the subscribe method is called, an independent execution of the observable happens.  

5. What is AOT Compilation?

Every angular application gets compiled internally. The angular compiler takes javascript code, compiles it and produces javascript code again. Ahead-of-Time Compilation does not happen every time or for every user, as is the case with Just-In-Time (JIT) Compilation. 

6. Why Typescript with Angular? 

Typescript is a superset of Javascript. Earlier, Javascript was the only client side language supported by all browsers. But, the problem with Javascript is, it is not an Object Oriented Programming Language. Typescript was thus developed by Microsoft in a way that it can work as Javascript and also offer what javascript cannot; i.e., OOPS. 

7. What are Decorators?

 Decorators are functions that adds metadata to class members and functions. It was proposed in ES2016 and implemented in Typescript.

8. List the types of Data Binding supported by Angular5?

 Angular 5 supports four types of Data Binding They are

(i) String Interpolation

(ii) Property Binding

(iii) Event Binding

(iv) Two-way-binding

9. How do we import a module in Angular5?

Simply use below syntax to import a module in Angular5.

import { ModuleName } from 'someWhere';

10. Name the building blocks of Angular.

The Angular application is made using the following: 

(i) Modules

(ii) Component

(iii) Template

(iv) Directives

(v) Data Binding

(vi) Services

(vii) Dependency Injection

(viii) Routing

11. Interpolation, Property Binding & Event Binding?

Interpolation allows you to define properties in a component class, and communicate these properties to and from the template.

Property binding is the same thing as interpolation, except you can set the properties and attributes of various HTML elements.

Event binding allows you to define events that occur in the template (user-initiated), and communicate to the component class. 

12. Observables : Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its http client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). Observables are a proposed feature for ES 2016, the next version of JavaScript.

13. Difference between Promises and Observables?

Promises:

return a single value

not cancellable

more readable code with try/catch and async/await


Observables:

work with multiple values over time

cancellable

support map, filter, reduce and similar operators

use Reactive Extensions (RxJS)

an array whose items arrive asynchronously over time

14. Module : In Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application.

Another analogy to understand Angular modules is classes. In a class, we can define public or private methods.

15. Components : Components are like the basic building block in an Angular application. Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.

16. Template : It is responsible for the UI part.

17. Directives : Alternatively, like a function in a programming language, you can write the code and later you can call it anytime whenever you want that behavior of that function. Similarly, you can create a directive and write the behavior inside it. Then, wherever you need that behavior, you can import the directive.

18. Routing : Routing basically means navigate from one view to another view in the application You have seen many sites with links that direct you to a new page. 

19. Dependency Injection : Dependency Injection (DI) is a way to create objects that depend upon other objects. A Dependency Injection system supplies the dependent objects (called the dependencies) when it creates an instance of an object.

In another way, When module A in an application needs module B to run, then module B is a dependency of module A.

20. Promises : Promises help us with asynchronicity (is that a word?) in Javascript. They are a way to say: "Hey, I'll tell you when this function completes, and if it doesn't I can throw an error". This is helpful because unlike in other languages, javascript statements can execute all at the same time, without waiting on the other to finish first.

21. What is Providers in angular 4?

Providers are usually singleton (one instance) objects, that other objects have access to through dependency injection (DI).

If you plan to use an object multiple times, for example Http service in different components, you can ask for same instance of that service (reuse it). You do that with the help of DI by providing a reference to the same object that DI creates for you.

@Component){

  ..

  providers: [Http]

}

..instead of creating new object every time:

@Component){}

class Cmp {

  constructor() {

    // this is pseudo code, doens't work

    this.http = new Http(...options);

  }

}

This is an approximation, but that's the general idea behind Dependency Injection - let the framework handle creation and maintenance of reusable objects... Provider is Angular's term for these reusable objects (dependencies).

22. What is component decorators?

They are just functions that can be used to add meta-data, properties or functions to the thing they are attached to.

Decorators are a new feature of TypeScript and used throughout the Angular code, but they are nothing to be scared of.

With decorators we can configure and customise our classes at design time.

23. interpolation "injects" the value into the html, so when you say value="{{ hello }}" Angular is inserting your variable between the brackets.

24. property binding allows Angular to directly access the elements property in the html. this is a deeper access. When you say [value]="hello" Angular is grabbing the value property of the element, and setting your variable as that property's value.

25. Event binding allows you to use events such as a click to trigger functions. these bindings use parenthesis for example (click)="myFunction($event)". this will call the myFunction() method on defined in your .ts file. the parenthesis around '(click)' bind the function to the dom event.$event is a keyword passing the event object to the function. you could also pass a string with single quotes, or even a variable with interpolation.

26. Two way (data) binding allows you to have an event combined with a property binding. For example

<input [(ngModel)]="username">

<p>Hello {{username}}!</p>

will allow you to have an input and display the value at the same time. learn more here

Lastly when to use interpolation and when to use data-binding. This is usually a formality, typically when using a smart component and dumb (presentation) component, you would bind to the html with property binding because of readability, and because it is shall I say, "more secure" to bind to a property in that case. If you have simple values, then maybe interpolation is your friend. It all comes down to readability, best practice, and preference.

27. What is the difference between component and directive?

Components have their own view (HTML and styles).

Directives are just "behaviour" added to existing elements and components.

28. What is Decorators? and Types of Decorators?

With decorators we can configure and customise our classes at design time.

They are just functions that can be used to add meta-data, properties or functions to the thing they are attached to.

Types of Decorators:

class , parameter, method and property

29. Promises :

Promises in JavaScript are a powerful concept that allow us to essentially write asynchronous code in a synchronous fashion and therefore provide us with additional benefits such as the elimination of the callback hell (aka pyramid of doom).

Promises are also using .then() methods which expect a callback to handle the resolved value. One key feature of promises is that when a Promise object returns another Promise object we can call .then() method on it again, effectively this allows us to chain .then() calls.

const urls = [

  'https://swapi.co/api/people/1',

  'https://swapi.co/api/people/4'

];

Promise.all(urls.map(url => {

  return fetch(url)

    .then(response => response.json())

    .then(response => console.log(response.name))

    .catch(error => console.error(error))

}));

30. Angular 5 Release: What's New?

1. Support for Multiple Export Alias in Angular 5

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

@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css'],

  exportAs:'dashboard, logBoard'

})

2. Internationalized Number, Date, and Currency Pipes

3. Improved Decorator Support in Angular 5

4. Build Optimization

5. Faster Compiler in Angular 5

31. Element directives - Directive activates when a matching element is encountered.

Attribute - Directive activates when a matching attribute is encountered.

CSS - Directive activates when a matching css style is encountered.

Comment - Directive activates when a matching comment is encountered.

32. DIFFERENCE BETWEEN COMPONENT AND DIRECTIVE IN ANGULAR 4

Ans:

Components

Directive

For register component we use @Component meta-data annotation.

For register directives we use @Directive meta-data annotation.


Component is a directive which use shadow DOM to create encapsulate visual behavior called components.  Components are typically used to create UI widgets.


Directives is used to add behavior to an existing DOM element.



Component is used to break up the application into smaller components.


Directive is use to design re-usable components.

Only one component can be present per DOM element.


Many directive can be used in a per DOM element.

@View decorator or templateurl template are mandatory in the component.


Directive don’t have View.

Component is used to define pipes.


You can’t define Pipes in directive.

viewEncapsulation can be define in components because they have views.

Directive don’t have views. So you can’t use viewEncapsulation in directive.

Example –


import {Component, View} from 'angular2/angular2';


@Component({

  selector: 'message'

})

@View({

  template: `

      <h1>Hello Angular {{version}}</h1>

  `

})

class Message {

  constructor(public version: string) {}

}


<message></message>

Example –


import {Directive} from 'angular2/angular2';


@Directive({

    selector: "[myDirective]",

    hostListeners: {

        'click': 'showMessage()'

    }

})

class Message {


    constructor() {}


    showMessage() { console.log('Hello Directive'); }

}


<button myDirective>Click here</button>


LINQ Interview Questions and Answers

 1. What are LINQ query expressions?

A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.

2. Write the basic steps to execute a LINQ query.

The following are the three basic steps to execute a LINQ query:

  • Obtain the data source (The data source can be either an SQL database or an XML file)

  • Create a query

  • Execute the query

3. Write the basic syntax of a LINQ query in Visual Basic as well as in C#.

In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

4. In which statement the LINQ query is executed?

A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#.

5. What is the function of the DISTINCT clause in a LINQ query?

The DISTINCT clause returns the result set without the duplicate values.

6. What is the difference between the Take and Skip clauses?

The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.

7. Which interface implements the standard query operators in LINQ?

The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface in C# and theIEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.

8. On what parameter does the GroupBy clause group the data?

The GroupBy clause groups the elements that share a common attribute.

9. What is a LinqDataSource control?

The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource andObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, theLinqDataSource control is designed to bind a LINQ enabled data model.

10. How can you open the O/R Designer?

You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.

11. The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable<T> interface in Visual Basic. Is it True or False?

False, as it implements the IEnumerable(T) interface in Visual Basic and the IEnumerable<T> interface is implemented in C#.

12. What are lambda expressions in LINQ?

A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.

13. Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this?

You can load the data into the dataset by using different methods, such as:

  • Using the DataAdapter class

  • Using LINQ to SQL

14. What are the different implementations of LINQ?

The different implementations of LINQ are:

  • LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.

  • LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.

  • LINQ to XML - Provides an in-memory XML programming interface.

  • LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.

15. Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework?

The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.

16. Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.

17. What is the difference between the Select clause and SelectMany() method in LINQ?

Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query.

18. Which extension method do you need to run a parallel query in PLINQ?

The AsParallel extension method is required to run a parallel query in PLINQ.

19. Difference in IEnumerable and IQueryable?

The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements based on query only. Let's may be you have asked for 1 record only by saying emplist.Take(1); In this case IEnumerable will iterate all elements but IQueryable will use Top 1 as a clause to fire a query.

When using IQueryable, the LINQ query gets used by IQueryProvider. This must be interpreted or compiled in order to get the result. This mean the delegate it receives is an expression tree instead of a method to invoke.

IEnumerable is great for working with in-memory collections, but IQueryable<t> allows for a remote data source, like a database or web service.

First thing linq is not a class. It's a namespace. There are different members which are included in System.Linq namespace like Enumerable, Querable, Lookup<>

20. Difference in AsEnumerable() vs AsiQueryable() Linq?

Enumerate means it will loop through the collection. This mean IEnumerable will loop thourgh all elements where as IQueryable will loop based on condition only.

Expression trees represent code in a tree-like data structure, where each node is an expression. So it will execute tree structured expression instead of invking the function.

21. Difference Between First() and FirstOrDefault() in LINQ?

A. First()

  1. When we Use First() in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Expression in Where Clause then It Will Throw You Exception as:InvalidOperationException: Sequence contains no elements.

  2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

  3. First() returns First Element Of Sequence.

  4. First() throws Exception when There IS No element Presnt In Table.

B. FirstORDefault():

1. When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null).

2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().

  1. FirstOrDefault () returns First Element Of Sequence.

  2. FirstOrDefault () does not throws Exception when There IS No element Present in Table.

22. Understanding Single, SingleOrDefault, First and FirstOrDefault?

Single

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection.

SingleOrDefault

It returns a single specific element from a collection of elements if element match found. An exception is thrown, if more than one match found for that element in the collection. A default value is returned, if no match is found for that element in the collection.

First

It returns first specific element from a collection of elements if one or more than one match found for that element. An exception is thrown, if no match is found for that element in the collection.

FirstOrDefault

It returns first specific element from a collection of elements if one or more than one match found for that element. A default value is returned, if no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault

  1. You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:
  2. When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  3. When you want a default value is returned if the result set contains no record, use SingleOrDefault.
  4. When you always want one record no matter what the result set contains, use First or FirstOrDefault.
  5. When you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.


23. Difference between iEnumerable and iEnumerator in c# .net?

Ans : We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example

To better understand we will create a list of age

List<int> ages = new List<int>();

ages.Add(10);

ages.Add(20);

ages.Add(30);

ages.Add(40);

ages.Add(50);

Now convert this list to IEnumerable

IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;

foreach (int age in age_IEnumerable)

{

    Console.WriteLine(age);

}

There is nothing new, we used foreach here very straight forward, now let’s convert the ages into IEnumerator, there is a method GetEnumerator to convert a list into IEnumerator

IEnumerator<int> age_IEnumerator = ages.GetEnumerator();

while (age_IEnumerator.MoveNext())

{

    Console.WriteLine(age_IEnumerator.Current);

}

As you can see here we used while rather than foreach because foreach cannot be used with IEnumerator, but still there is nothing which can suggest us when should we use IEnumerable and where to IEnumerator.


Before we go further, we should know, IEnumerable uses IEnumerator internally also have a function GetEnumerator to convert into IEnumerator, we should use IEnumerable because it make coding easier and clearer as we can see in above example.


Now let’s discuss the main difference, IEnumerable doesn’t remember the state, which row or record it is iterating while IEnumerator remember it and we are going to see this with example by creating method PrintUpto30 and PrintGreaterThan30


Let’s first check with IEnumerator


public void PrintAgeUpto30(IEnumerator<int> age_IEnumerator)

{

   while (age_IEnumerator.MoveNext()){

      Console.WriteLine(age_IEnumerator.Current);

      if (age_IEnumerator.Current > 20) {

         Console.WriteLine("PrintGreaterThan30 is called");

         PrintGreaterThan30(age_IEnumerator);

      }

   }

}


public void PrintGreaterThan30(IEnumerator<int> age_IEnumerator)

{

    while (age_IEnumerator.MoveNext())

        Console.WriteLine(age_IEnumerator.Current);

}

// Now Call PrintUpto30 which will call PrintGreaterThan30 

// by using our previous age IEnumerator

PrintUpto30(IEnumerator);

As we know IEnumerator persists state so once we will call PrintGreaterThan30 by passing age_IEnumerator it will print the remaining list, here is the output:


10

20

30

PrintGreaterThan30 is called

40

50

Now let’s check same code with IEnumerable


public void PrintUpto30(IEnumerable<int> age_IEnumerable)

{

    foreach (int age in age_IEnumerable){

       Console.WriteLine(age);

       if (age > 20){

         Console.WriteLine("PrintGreaterThan30 is called");

        PrintGreaterThan30(age_IEnumerable);

      }

   }

}


public void PrintGreaterThan30(IEnumerable<int> age_IEnumerable)

{

  foreach (int age in age_IEnumerable)

    Console.WriteLine(age);

}

// Now Call PrintUpto30 by using our variable age_IEnumerable


PrintAgeUpto30(age_IEnumerable);

Now check the output you will see “PrintGreaterThan30 is called” many times something like this


10

20

30

PrintGreaterThan30 is called

10

....

50

40

PrintGreaterThan30 is called

10

...

50

50

PrintGreaterThan30 is called

10

50


Conclusion:

  1. Both are interface

  2. IEnumerable code are clear and can be used in foreach loop

  3. IEnumerator use While, MoveNext, current to get current record

  4. IEnumerable doesn’t remember state

  5. IEnumerator persists state means which row it is reading

  6. IEnumerator cannot be used in foreach loop

  7. IEnumerable defines one method GetEnumerator which returns an IEnumerator

  8. IEnumerator allows readonly access to a collection


24. What is difference between .edmx and .dbml file in linq?

edmx is the modeling file for Entity Framework.

dbml is the modeling file for Linq 2 Sql.


25. Join in linq C#?

var query =

  from department in departments

  join employee in employees

      on department.ID equals employee.DepartmentID 

  select new { employee.Name, Department = department.Name };


26. Left Outer Join and Right Outer Join in LINQ

//Left join

var Ljoin = from emp in ListOfEmployees

join proj in ListOfProject

on emp.ProjectID equals proj.ProjectID into JoinedEmpDept

from proj in JoinedEmpDept.DefaultIfEmpty()

select new

{

EmployeeName = emp.Name,

ProjectName = proj != null ? proj.ProjectName : null

};


//Right outer join

var RJoin = from proj in ListOfProject

join employee in ListOfEmployees

on proj.ProjectID equals employee.ProjectID into joinDeptEmp

from employee in joinDeptEmp.DefaultIfEmpty()

select new

{

EmployeeName = employee != null ? employee.Name : null,

ProjectName = proj.ProjectName

};


Perform Left Outer Joins in LINQ?

var query = from person in people

join pet in pets on person equals pet.Owner into gj

from subpet in gj.DefaultIfEmpty()

select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };


foreach (var v in query)

{

Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);

}


OR


var query =

from  u in Repo.T_Benutzer

join bg in Repo.T_Benutzer_Benutzergruppen

on u.BE_ID equals bg.BEBG_BE

into temp

from j in temp.DefaultIfEmpty()

select new

{

BE_User = u.BE_User,

BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG

//, bg.Name

}

Simple Join


var query =

from post in database.Posts

join meta in database.Post_Metas on post.ID equals meta.Post_ID

where post.ID == id

select new { Post = post, Meta = meta };


Constructor

1. What is a Constructor in C#? A constructor is a special method that runs when an object of a class is created. It initializes the object ...