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>


No comments:

Post a Comment

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 ...