InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Explain MVVM architecture |
|
Answer» MVVM architecture consists of three parts:
View and ViewModel are connected with data-binding (two-way data-binding in this case). Any change in the view, the viewmodel takes a note and changes the appropriate data inside the model. |
|
| 2. |
What is a bootstrapping module? |
|
Answer» Every application contains at least one Angular module, which is referred to as the bootstrapping module. AppModule is the most popular name for it. Example: The following is the default structure of an AngularCLI-generated AppModule: import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
|
| 3. |
What is Change Detection, and how does the Change Detection Mechanism work? |
|
Answer» The process of synchronizing a model with a view is known as Change Detection. Even when utilizing the ng Model to implement two-way binding, which is syntactic sugar on top of a unidirectional flow. Change detection is incredibly fast, but as an app's complexity and the number of components increase, change detection will have to do more and more work. Change Detection Mechanism-moves only ahead and never backward, beginning with the root component and ending with the last component. This is what one-way data flow entails. The tree of components is the architecture of an Angular application. Each component is a child, but the child is not a parent. A $digest loop is no longer required with the one-way flow. |
|
| 4. |
What is AOT compilation? What are the advantages of AOT? |
|
Answer» Every Angular application consists of components and templates that the browser cannot understand. Therefore, all the Angular applications need to be compiled first before running inside the browser. Angular provides two types of compilation:
In JIT compilation, the application compiles inside the browser during runtime. Whereas in the AOT compilation, the application compiles during the build time. The advantages of using AOT compilation are:
By default, angular builds and serves the application using JIT compiler: ng buildng serve For using AOT compiler following changes should be made: ng build --aotng serve --aot |
|
| 5. |
What are HTTP interceptors ? |
|
Answer» Using the HttpClient, interceptors allow us to intercept incoming and outgoing HTTP requests. They are capable of handling both HttpRequest and HttpResponse. We can edit or update the value of the request by intercepting the HTTP request, and we can perform some specified actions on a specific status code or message by intercepting the answer. Example: In the following example we will set the Authorization header Bearer for all the requests: token.interceptor.tsimport { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class TokenInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const token = localStorage.getItem('token') as string; if (token) { req = req.clone({ setHeaders: { 'Authorization': `Bearer ${token}` } }); } return next.handle(req); } } We have to register the interceptor as singleton in the module providers app.module.tsimport { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AppComponent } from './app.component'; import { TokenInterceptor } from './token.interceptor'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [AppComponent], providers: [{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true }] }) export class AppModule {} |
|
| 6. |
What is transpiling in Angular ? |
|
Answer» Transpiling is the process of transforming the source code of one programming language into the source code of another. Typically, in Angular, this implies translating TypeScript to JavaScript. TypeScript (or another language like as Dart) can be used to develop code for your Angular application, which is subsequently transpiled to JavaScript. This occurs naturally and internally. |
|
| 7. |
What is ngOnInit? |
|
Answer» ngOnInit is a lifecycle hook and callback function used by Angular to mark the creation of a component. It accepts no arguments and returns a void type. Example: export class MyComponent implements OnInit {constructor() { } ngOnInit(): void { //.... } } |
|
| 8. |
What does Angular Material means? |
|
Answer» Angular Material is a user interface component package that enables professionals to create a uniform, appealing, and fully functioning websites, web pages, and web apps. It does this by adhering to contemporary web design concepts such as gentle degradation and browser probability. |
|
| 9. |
What exactly is the router state? |
|
Answer» RouterState is a route tree. This tree's nodes are aware of the "consumed" URL segments, retrieved arguments, and processed data. You may use the Router service and the routerState property to get the current RouterState from anywhere in the application. Example: @Component({templateUrl:'example.html'})class MyComponent { constructor(router: Router) { const state: RouterState = router.routerState; const root: ActivatedRoute = state.root; const child = root.firstChild; const id: Observable<string> = child.params.map(p => p.id); //... } } |
|
| 10. |
What are router links? |
|
Answer» RouterLink is an anchor tag directive that gives the router authority over those elements. Because the navigation routes are set. Example: As seen below, you may pass string values to the router-link directive. <h1>Example of an Angular Router</h1><nav> <a routerLink="/home" >Home Page of our website</a> <a routerLink="/about-us" >About us</a> </nav> <router-outlet></router-outlet> |
|
| 11. |
What are lifecycle hooks in Angular? Explain a few lifecycle hooks. |
|
Answer» Every component in Angular has a lifecycle, and different phases it goes through from the time of creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger changes at specific phases in a lifecycle.
Let’s understand how to use ngOnInit hook, since it’s the most often used hook. If one has to process a lot of data during component creation, it’s better to do it inside ngOnInit hook rather than the constructor: import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { constructor() { } ngOnInit() { this.processData(); } processData(){ // Do something.. } } As you can see we have imported OnInit but we have used ngOnInit function. This principle should be used with the rest of the hooks as well. |
|
| 12. |
What is the Component Decorator in Angular? |
|
Answer» TypeScript classes are used to create components. This class genre is then decorated with the "@Component" decorator. The decorator's function is to take a metadata object holding component information and decorate it. A Decorator is always preceded by @. The Decorator must come before the class definition. We can also make our own decorators. Example: The example below shows us a Class decorated with the @Component decorator. import {Component} from '@angular/core';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Example component'; } The metadata object received by the decorator has values such as templateUrl, selector, and others, with the templateUrL property pointing to an HTML file that defines what you see on the application. |
|
| 13. |
What are property decorators? |
|
Answer» These are the second most popular types of decorators. They enable us to enhance some of the properties in our classes. We can certainly understand why we utilize any certain class property by using a property decorator. There are many property decorators available for example @Input(), @Output, @ReadOnly(), @Override() Example: import { Component, Input } from '@angular/core';@Component({ selector: 'prop-component', template: '<div> This is a test component ! </div>' }) export class PropComponent { @Input() exampleProperty: string; } The input binding would be sent via a component property binding: <prop-component[propProperty]="propData"> </prop-component> |
|
| 14. |
What are Method decorators? |
|
Answer» Method decorators, as the name implies, are used to add functionality to the methods defined within our class. Example: @HostListener, is a good example of method decorators. import { Component, HostListener } from '@angular/core';@Component({ selector: 'method-component', template: '<div> This is a test method component ! </div>', }) export class MethodComponent { @HostListener('click', ['$event']) onHostClick(event: Event) { console.log('clicked now this event is available !'); } } The @HostListener decorator is used before the onHostClick () method in the above example code. |
|
| 15. |
What are class decorators? |
|
Answer» Class Decorators are the highest-level decorators that determine the purpose of the classes. They indicate to Angular that a specific class is a component or module. And the decorator enables us to declare this effect without having to write any code within the class. Example: import { NgModule, Component } from '@angular/core';@Component({ selector: 'class-component', template: '<div> This is a class component ! </div>', }) export class ClassComponent { constructor() { console.log('This is a class component!'); } } @NgModule({ imports: [], declarations: [], }) export class ClassModule { constructor() { console.log('This is a class module!'); } } It is a component or module in which no code in the class is required to tell Angular. We only need to design it, and Angular will take care of the rest. |
|
| 16. |
What exactly is a parameterized pipe? |
|
Answer» To fine-tune its output, a pipe can receive any number of optional parameters. The parameterized pipe is constructed by first stating the pipe name followed by a colon (:) and then the parameter value. If the pipe supports several arguments, use colons to separate the values. Example: Let's look at a birthday with a certain format (dd/MM/yyyy): import { Component } from '@angular/core';@Component({ selector: 'app-example', template: `<p>Birthday is {{ birthday | date:'dd/MM/yyyy'}}</p>` }) export class ExampleComponent { birthday = new Date(2000, 7, 15); } |
|
| 17. |
What are pipes in Angular explain with an example? |
|
Answer» Pipes are functions that simplify the process of wiring up your JavaScript expressions and transforming them into their desired output. They can be compared to, say, string functions in other programming languages. Pipes also allow you to combine multiple expressions together, whether they're all values or some values and some declarations. For example: var css = myTheme.color | "red" ; This line would assign a value to css , and it's equivalent to writing out the following code: Pipes have several built-in functions that allow you to transform data, such as value and extract. We can also create our own custom pipes. Pipes are data transformers that execute on an Angular Component's output. They take in data and return transformed data. For example, if you have an expression such as number | 1000, the number pipe will take data from the output and transform it into 1000. In Angular, there are many built-in pipes that you can use. You can also create your own custom pipes by implementing the PipeTransform interface in a class. Pipes receive an input which can be a value expression, a function returning an expression, or even a component property., that outputs a number with a value of 1,000. With a pipe, you can transform this output into a formatted string of "1,000" or "1.000". Example: import { Component } from '@angular/core';@Component({ selector: 'app-root', template: `{{ title | uppercase}}`, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'this is an example of custom pies in angular'; } Output: THIS IS AN EXAMPLE OF CUSTOM PIPES IN ANGULAR |
|
| 18. |
Explain the concept of Dependency Injection? |
|
Answer» Dependency injection is an application design pattern which is implemented by Angular. It also forms one of the core concepts of Angular. So what is dependency injection in simple terms? Let’s break it down, dependencies in angular are nothing but services which have functionality. The functionality of a service, can be needed by various components and directives in an application. Angular provides a smooth mechanism by which we can inject these dependencies into our components and directives. So basically, we are just making dependencies which are injectable across all components of an application. Let’s understand how DI (Dependency Injection) works: Consider the following service, which can be generated using: ng g service test import { Injectable } from '@angular/core';@Injectable({ providedIn: 'root' }) export class TestService { importantValue:number = 42; constructor() { } returnImportantValue(){ return this.importantValue; } } As one can notice, we can create injectable dependencies by adding the @Injectable decorator to a class. We inject the above dependency inside the following component: import { TestService } from './../test.service';import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { value:number; constructor(private testService:TestService) { } ngOnInit() { this.value = this.testService.returnImportantValue(); } } One can see we have imported our TestService at the top of the page. Then, we created an instance inside the constructor of the component and implemented the returnImportantValue function of the service. From the above example, we can observe how angular provides a smooth way to inject dependencies in any component. |
|
| 19. |
How are observables different from promises? |
||||||||||
|
Answer» The first difference is that an Observable is lazy whereas a Promise is eager.
Consider the following Observable: const observable = rxjs.Observable.create(observer => {console.log('Text inside an observable'); observer.next('Hello world!'); observer.complete(); }); console.log('Before subscribing an Observable'); observable.subscribe((message)=> console.log(message)); When you run the above Observable, you can see messages being displayed in the following order: Before subscribing an ObservableText inside an observable Hello world! As you can see, observables are lazy. Observable runs only when someone subscribes to them hence, the message “Before subscribing…” is displayed ahead of the message inside the observable. Now let’s consider a Promise: const promise = new Promise((resolve, reject) => {console.log('Text inside promise'); resolve('Hello world!'); }); console.log('Before calling then method on Promise'); greetingPoster.then(message => console.log(message)); Running the above promise, the messages will be displayed in the following order: Text inside promiseBefore calling then method on Promise Hello world! As you can see the message inside Promise is displayed first. This means that a promise runs before the then method is called. Therefore, promises are eager. The next difference is that Promises are always asynchronous. Even when the promise is immediately resolved. Whereas an Observable, can be both synchronous and asynchronous. The above example of an observable is the case to show that an observable is synchronous. Let’s see the case where an observable can be asynchronous: const observable = rxjs.Observable.create(observer => {setTimeout(()=>{ observer.next('Hello world'); observer.complete(); },3000) }); console.log('Before calling subscribe on an Observable'); observable.subscribe((data)=> console.log(data)); console.log('After calling subscribe on an Observable'); The messages will be displayed in the following order: Before calling subscribe on an ObservableAfter calling subscribe on an Observable Hello world! You can see in this case, observable runs asynchronously. The next difference is that Observables can emit multiple values whereas Promises can emit only one value. The biggest feature of using observables is the use of operators. We can use multiple operators on an observable whereas, there is no such feature in a promise. |
|||||||||||
| 20. |
Explain string interpolation and property binding in Angular. |
Answer»
|
|
| 21. |
What are RxJs in Angular ? |
|
Answer» RxJS is an acronym that stands for Reactive Extensions for JavaScript. It is used to enable the use of observables in our JavaScript project, allowing us to do reactive programming. RxJS is utilized in many popular frameworks, including Angular since it allows us to compose our asynchronous or callback-based code into a sequence of operations executed on a data stream that releases values from a publisher to a subscriber. Other programming languages, such as Java and Python, offer packages that allow them to develop reactive programs utilizing observables. Most of the time, rxJs is used in HTTP calls with angular. Because http streams are asynchronous data, we can subscribe to them and apply filters to them. Example: The following is a simple example of how RxJs can be utilized with HTTP calls. let stream1 = httpc.get("https://www.example.com/somedata");let stream2 = stream1.pipe(filter(x=>x>3)); stream2.subscribe(res=>this.Success(res),res=>this.Error(res)); |
|
| 22. |
What is view encapsulation in Angular? |
|
Answer» View encapsulation specifies if the component's template and styles can impact the entire program or vice versa. Angular offers three encapsulation methods:
|
|
| 23. |
What is Eager and Lazy loading? |
Answer»
|
|
| 24. |
Angular by default, uses client-side rendering for its applications. |
|
Answer» Can one make an angular application to render on the server-side? Yes, angular provides a technology called Angular Universal, which can be used to render applications on the server-side. The advantages of using Angular Universal are:
|
|