Angular Interview Question

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

What is the difference between pure and impure pipe?

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.

What is a service?

A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components. Let's create a repoService which can be used across components,

What is activated route?

ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. In the below example, you can access route path and parameters, @Component({...}) class MyComponent { constructor(route: ActivatedRoute) { const id: Observable<string> = route.params.pipe(map(p => p.id)); const url: Observable<string> = route.url.pipe(map(segments => segments.join(''))); // route.data includes both `data` and `resolve` const user = route.data.pipe(map(d => d.user)); } }

What is AOT?

Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time. For AOT compilation, include the --aot option with the ng build or ng serve command as below, ng build --aot ng serve --aot Note: The ng build command with the --prod meta-flag (ng build --prod) compiles with AOT by default.

What is subscribing?

An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

What is Angular Router?

Angular Router is a mechanism in which navigation happens from one view to the next as users perform application tasks. It borrows the concepts or model of browser's application navigation.

What is Angular Framework?

Angular is a TypeScript-based open-source front-end platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.

What are different types of compilation in Angular?

Angular offers two ways to compile your application, Just-in-Time (JIT) Ahead-of-Time (AOT)

What are the major difference between AngularJS Angular?

AngularJS Angular It is based on MVC architecture This is based on Service/Controller This uses use JavaScript to build the application Introduced the typescript to write the application Based on controllers concept This is a component based UI approach Not a mobile friendly framework Developed considering mobile platform Difficulty in SEO friendly application development Ease to create SEO friendly applications

What are the advantages with AOT?

Below are the list of AOT benefits, Faster rendering: The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app. Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests. Smaller Angular framework download size: Doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload. Detect template errors earlier: Detects and reports template binding errors during the build step itself Better security: It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.

What are components?

Components are the most basic UI building block of an Angular app which formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. Let's see a simple example of Angular component

How many ways are there for observable creation functions?

Create an observable from a promise create an observable that creates an AJAX request create an observable from a counter create an observable from an event

What is a data binding?

Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing. From the Component to the DOM: Interpolation: {{ value }}: Adds the value of a property from the component <li>Name: {{ user.name }}</li> <li>Address: {{ user.address }}</li> Property binding: [property]="value": The value is passed from the component to the specified property or simple HTML attribute <input type="email" [value]="user.email"> From the DOM to the Component: Event binding: (event)="function": When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component <button (click)="logout()"></button> Two-way binding: Two-way data binding: [(ngModel)]="value": Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync <input type="email" [(ngModel)]="user.email">

What is dependency injection in Angular?

Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.

What are directives

Directives add behaviour to an existing DOM element or an existing component instance. import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } }

What are dynamic components?

Dynamic components are the components in which components location in the application is not defined at build time.i.e, They are not used in any angular template. But the component is instantiated and placed in the application at runtime.

What are the restrictions of metadata?

In Angular, You must write metadata with the following general constraints, Write expression syntax with in the supported range of javascript features The compiler can only reference symbols which are exported Only call the functions supported by the compiler Decorated and data-bound class members must be public.

What are the differences between Component and Directive?

In a short note, A component(@component) is a directive-with-a-template. Some of the major differences are mentioned in a tabular form Component Directive To register a component we use @Component meta-data annotation To register directives we use @Directive meta-data annotation Components are typically used to create UI widgets Directive 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 directives can be used per DOM element @View decorator or templateurl/template are mandatory Directive doesn't use View

What is JIT?

Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation is the default when you run the ng build (build only) or ng serve (build and serve locally) CLI commands. i.e, the below commands used for JIT compilation, ng build ng serve

What is lazy loading?

Lazy loading is one of the most useful concepts of Angular Routing. It helps us to download the web pages in chunks instead of downloading everything in a big bundle. It is used for lazy loading by asynchronously loading the feature module for routing whenever required using the property loadChildren. Let's load both Customer and Order feature modules lazily as below, { path: 'customers', loadChildren: () => import('./customers/customers.module').then(module => module.CustomersModule) },

What is metadata?

Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators There are four types: 1. Class decorators, e.g. @Component and @NgModule 2. Property decorators Used for properties inside classes, e.g. @Input and @Output 3. Method decorators Used for methods inside classes, e.g. @HostListener 4. Parameter decorators Used for parameters inside class constructors, e.g. @Inject

What is HttpClient and its benefits?

Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is avaialble from @angular/common/http package. You can import in your root module as below, import { HttpClientModule } from '@angular/common/http';

What is multicasting?

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature Basically we would use Subject to *being* multi cast Subject can subscript to multiple places. But it would not excute like observable. It would excute when the next of the Subject being run outside. It's kind of like revers of obervable **A multicasted Observable uses a Subject under the hood to make multiple Observers see the same Observable execution.

What is the purpose of async pipe?

Normally to render the result of a promise or an observable we have to: 1. Wait for a callback. 2. Store the result of the callback is a variable. 3. Bind to that variable in the template. With AsyncPipe we can use promises and observables directly in our template, without having to store the result on an intermediate property or variable. AsyncPipe accepts as argument an observable or a promise, calls subscribe or attaches a then handler, then waits for the asynchronous result before passing it through to the caller.

What is the difference between promise and observable?

Observable Promise Declarative: Computation does not start until subscription so that they can be run whenever you need the result Execute immediately on creation Provide multiple values over time Provide only one Subscribe method is used for error handling which makes centralized and predictable error handling Push errors to the child promises Provides chaining and subscription to handle complex applications Uses only .then() clause

What are observables?

Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

What is an observer?

Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure, interface Observer<T> { closed?: boolean; next: (value: T) => void; error: (err: any) => void; complete: () => void; }

What is RxJS?

RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables. For example, you can import observables and operators for using HttpClient as below, import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators';

What are observable creation functions? How do you convert a promise into a observable?

RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. By using from import { from } from 'rxjs'; // from function const data = from(fetch('/api/endpoint')); //Created from Promise data.subscribe({ next(response) { console.log(response); }, error(err) { console.error('Error: ' + err); }, complete() { console.log('Completed'); } });

? is a

Safe Navigation Operator Safe navigation operator avoids exception for null and undefined values in property paths. While accessing properties from object it may throw exception if object is null or undefined. For safer side we can use safe navigation operator to access property from object and hence it will not throw exception for the scenario that object is null or undefined. If we have an object person with the properties name then using safe navigation operator we will access object property as follows.

What are the router imports?

The Angular Router which represents a particular component view for a given URL is not part of Angular Core. It is available in library named @angular/router to import required router components. For example, we import them in app module as below, import { RouterModule, Routes } from '@angular/router';

Why do we need compilation process?

The Angular components and templates cannot be understood by the browser directly. Due to that Angular applications require a compilation process before they can run in a browser. For example, In AOT compilation, both Angular HTML and TypeScript code converted into efficient JavaScript code during the build phase before browser runs it.

What are router links?

The RouterLink is a directive on the anchor tags give the router control over those elements. Since the navigation paths are fixed, you can assign string values to router-link directive as below, <h1>Angular Router</h1> <nav> <a routerLink="/todosList" >List of todos</a> <a routerLink="/completed" >Completed todos</a> </nav> <router-outlet></router-outlet>

What is router outlet?

The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used like a component, <router-outlet></router-outlet> <!-- Routed components go here -->

BehaviorSubject

The RxJS BehaviorSubject is a special type of Subject that keeps hold of the current value and emits it to any new subscribers as soon as they subscribe, while regular Subjects don't store the current value and only emit values that are published after a subscription is created.

What are the utility functions provided by RxJS?

The RxJS library also provides below utility functions for creating and working with observables. 1. Converting existing code for async operations into observables 2. Iterating through the values in a stream 3. Mapping values to different types 4. Filtering streams 5. Composing multiple streams

How can you read full response of HTTP Client?

The response body doesn't may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. Inorder to get full response, you should use observe option from HttpClient, getUserResponse(): Observable<HttpResponse<User>> { return this.http.get<User>( this.userUrl, { observe: 'response' }); }

What is the purpose of base href tag?

The routing application should add element to the index.html as the first child in the tag inorder to indicate how to compose navigation URLs. If app folder is the application root then you can set the href value as below <base href="/">

<ng-template>

These template elements only work in the presence of structural directives. Angular wraps the host element (to which the directive is applied) inside <ng-template> and consumes the <ng-template> in the finished DOM by replacing it with diagnostic comments.

What is the difference between constructor and ngOnInit?

TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method. In order to use ngOnInit, you need to implement OnInit interface as below,

Promise.all(iterable)

Wait for all promises to be resolved, or for any to be rejected. If the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises in the same order as defined in the iterable of multiple promises. If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected. basically, if all need to be success otherwise it will reject for the first reason.

Promise.allSettled(iterable)

Wait until all promises have settled (each may resolve, or reject). Returns a Promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise. Basically the alternative of .all This one we will get all the result of resolve and rejected

Promise.race(iterable)

Wait until any of the promises is resolved or rejected. If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved. If it rejects, it is rejected with the reason from the first promise that was rejected. Basically all the promises race each other and whichever finished first will be returned.

How to chain pips?

You can chain pipes together in potentially useful combinations as per the needs. Let's take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below `<p>Birthday is {{ birthday | date:'fullDate' | uppercase}} </p>`

, the root module that you bootstrap to launch the application is called as bootstrapping module.

the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule


Kaugnay na mga set ng pag-aaral

Geometry: Unit 8 - practice questions

View Set

Modern India: Political Challenges

View Set

Study Guide / Text Questions (Chapter 3, 4,

View Set

ENVIRONMENTAL SCIENCE EXAM 4 CHAPTER 17

View Set

SOC-1113-22269 Exam 1 study guide

View Set

Unit 12 body system 4:The Male Reproductive System

View Set

Chapter 9 Class Test - Legal Descriptions

View Set

Chapter 22 - Performance and Breach of Sales and Lease Contracts

View Set

Business 150 Module 3 Study Guide

View Set

Chapter 20 Biology, Chapter 21 Biology, Chapter 22 Biology

View Set