Angular
Search…
Angular Questions And Answers

What is an observable?

Observables are declarative—that is, 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.
It is what we want to observe, which will be implemented through a collection of future events or values. An observable can be created from user events derived from the use of a form, an HTTP call, a data store, etc.
A representation of any set of values over any amount of time. This is the most basic building block of RxJS.

What are Lifecycle hooks in Angular? Explain some life cycles hooks

Answer: Angular components enter its lifecycle from the time it is created to the time it is destroyed. Angular hooks provide ways to tap into these phases and trigger changes at specific phases in a lifecycle.
ngOnChanges( ): This method is called whenever one or more input properties of the component changes. The hook receives a SimpleChanges object containing the previous and current values of the property.
ngOnInit( ): This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ): It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook.
ngAfterContentInit( ): It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ): It gets called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): It responds after a component's view, or a child component's view is initialized.
ngAfterViewChecked( ): It gets called after ngAfterViewInit, and it responds after the component's view, or the child component's view is checked.
ngOnDestroy( ): It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.

Could we make an angular application to render on the server-side?

Answer: Yes, we can, with Angular Universal, a technology provided by Angular capable of rendering applications on the server-side.

Explain Dependency Injection?

Dependency injection in Angular are services that have functionality. Various components and directives in an application can need these functionalities of the service. Angular provides a smooth mechanism by which these dependencies are injected into components and directives.

Demonstrate navigating between different routes in an Angular application.

Following code demonstrates how to navigate between different routes in an Angular app dubbed “Some Search App”:
1
import from "@angular/router";
2
.
3
.
4
.
5
@Component({
6
selector: 'app-header',
7
template: `
8
<nav class="navbar navbar-light bg-faded">
9
<a class="navbar-brand" (click)="goHome()">Some Search App</a>
10
<ul class="nav navbar-nav">
11
<li class="nav-item">
12
<a class="nav-link" (click)="goHome()">Home</a>
13
</li>
14
<li class="nav-item">
15
<a class="nav-link" (click)="goSearch()">Search</a>
16
</li>
17
</ul>
18
</nav>
19
`
20
})
21
class HeaderComponent {
22
constructor(private router: Router) {}
23
goHome() {
24
this.router.navigate(['']);
25
}
26
goSearch() {
27
this.router.navigate(['search']);
28
}
29
}
Copied!

What is the AOT (Ahead-Of-Time) Compilation? What are its advantages?

An angular application consists of components and templates which a browser cannot understand. Therefore, every Angular application needs to be compiled before running inside the browser. The Angular compiler takes in the JS code, compiles it, and then produces some JS code. It is known as AOT compilation and happens only once per occasion per user.
There are two kinds of compilation that Angular provides:
  1. 1.
    JIT(Just-in-Time) compilation: the application compiles inside the browser during runtime
  2. 2.
    AOT(Ahead-of-Time) compilation: the application compiles during the build time.

Advantages of AOT compilation:

  • Fast Rendering: The browser loads the executable code and renders it immediately as the application is compiled before running inside the browser.
  • Fewer Ajax Requests: The compiler sends the external HTML and CSS files along with the application, eliminating AJAX requests for those source files.
  • Minimizing Errors: Easy to detect and handle errors during the building phase.
  • Better Security: Before an application runs inside the browser, the AOT compiler adds HTML and templates into the JS files, so there are no extra HTML files to be read, thus providing better security for the application.

Explain change detection in Angular

  1. 1.
    How to trigger change detection manually?
  2. 2.
    What is the difference between detectChanges and markForCheck? Scenario: @Input changed and component has not been refreshed.

Answer 1

Angular's default change detection strategy may work well for a hobby app or presentation demo but if you're dealing with a large or enterprise application, you're likely going to take a performance hit. That's because by default Angular checks and detects everything rendered in the template. One of the ways we can solve this is by using manual change detection, however, it's not the best way.
True "manual" change detection in Angular would be a combination of the OnPush change detection strategy with methods like detectChanges(), detach(), markForCheck() and others in your components. This can be a great solution if you need full control over change detection. For instance, if you're getting data from a websocket you may want to use detectChanges() to limit how often you're checking for changes. If you don't need full control, however, it can certainly over-complicate things.

Name and explain some of lifecycle hooks

ngOnChanges( ): This method is called whenever one or more input properties of the component changes. The hook receives a SimpleChanges object containing the previous and current values of the property.
ngOnInit( ): This hook gets called once, after the ngOnChanges hook. It initializes the component and sets the input properties of the component.
ngDoCheck( ): It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular. We can implement our change detection algorithm in this hook.
ngAfterContentInit( ): It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ): It gets called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): It responds after a component's view, or a child component's view is initialized.
ngAfterViewChecked( ): It gets called after ngAfterViewInit, and it responds after the component's view, or the child component's view is checked.
ngOnDestroy( ): It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.
There's an Observable field in a component, it got subscribed to. Can you spot a memory leak? (it should be unsubscribed from in ngOnDestroy)

Explain the difference between an Annotation and a Decorator in Angular?

In Angular, annotations are used for creating an annotation array. They are only metadata set of the class using the Reflect Metadata library.
Decorators in Angular are design patterns used for separating decoration or modification of some class without changing the original source code.

Explain the differences between Observable and Promise

A Promise is always asynchronous, while an Observable can be either synchronous or asynchronous, a Promise can provide a single value, whereas an Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to an Observable to get a new tailored stream.

How do you cancel an Observable stream?

One of the key features of Observables is its ability to cancel the underlying operation of the source. In fact, the ReactiveX documentation explains the primary purpose of the Subscription as this.
Subscription: represents the execution of an Observable, is primarily useful for cancelling the execution.
However, if you have been using RxJS for long enough, this is not a concept that seems natural to Observables. The pattern seems to almost dictate that Subscriptions are simply a “viewership” to the source and not something that controls the source. This is mostly because of the different types of Observables that we come to use and our inability to always know what type an observable is and what really happens when you do unsubscribe from the Subscription.

What are hot and cold & hot Observables?

Hot observables

When you subscribe you are essentially just starting to listen. Similarly when you unsubscribe you are stopping your listening. Following is a classic example of a hot observable.
The observable is already working and streaming data. A realworld example might be when you enter in a life-stream movie, the movie is already streaming no matters if you are subscribed or not. Example, behaviorSubject

Cold observables

On cold observables, the observer starts the underlying operation for that observer with a subscribe. Similarly, the observer ends the underlying operation for that observer with an unsubscribe. Most creation operators create a cold observable.
The observable does not stream data to the subscriptor until such is subscribed. A realworld example might be if you visit Netflix and start a movie, the movie will be displayed when you "subscribe" to it.

How behaviorsubject works in angular?

BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
  • It needs an initial value as it must always return a value on subscription even if it hasn't received a next()
  • Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an onnext
  • at any point, you can retrieve the last value of the subject in a non-observable code using the getValue() method.
In addition, you can get an observable from behavior subject using the asObservable() method on BehaviorSubject.
1
// Behavior Subject
2
3
// a is an initial value. if there is a subscription
4
// after this, it would get "a" value immediately
5
let bSubject = new BehaviorSubject("a");
6
7
bSubject.next("b");
8
9
bSubject.subscribe(value => {
10
console.log("Subscription got", value); // Subscription got b,
11
// ^ This would not happen
12
// for a generic observable
13
// or generic subject by default
14
});
15
16
bSubject.next("c"); // Subscription got c
17
bSubject.next("d"); // Subscription got d
Copied!
1
// Regular Subject
2
3
let subject = new Subject();
4
5
subject.next("b");
6
7
subject.subscribe(value => {
8
console.log("Subscription got", value); // Subscription wont get
9
// anything at this point
10
});
11
12
subject.next("c"); // Subscription got c
13
subject.next("d"); // Subscription got d
Copied!