Angular

What is ngOnInit()?

ngOnInit( ) – This hook gets called once, after the ngOnChanges() hook. It initializes the component and sets the input properties of the component.

How are observables different from promises?

  • Observable is lazy whereas a Promise is eager.
  • Promise emits a single value, Observable emits multiple values over a period of time.
  • Promise is not Lazy. Observable is Lazy. An observable is not called until we subscribe to the observable.
  • Promise cannot be cancelled. Observable can be cancelled by using the unsubscribe() method. Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc.

What are directives in Angular?

A directive is a class in Angular that is declared with a @Directive decorator. Every directive has its own behavior and can be imported into various components of an application.

What are the Angular Route Guards and what to do with them?

As the name suggests, you can configure guards on routes in your application to control how a user navigates between them. These route gaurds (also called as functions) are called when router tries to activate or deactivate certain routes.

The general rule is that the guards are functions that are called in certain points of the router lifecycle. They return a boolean or an asynchronous response: Promise or Observable. In the case of CanActivate, the guard function is called when a user tries to navigate into the route. The component behind it will only be activated after the function returns true or the Observable/Promise will eventually return true. When the function hangs or returns false, the router will not display the route content.

What are the names of some tools used for testing Angular applications?

For testing Angular applications there are certain tools that you should use that will make testing much easier to set up and run.

Karma

Karma is a JavaScript command line tool that can be used to spawn a web server which loads your application’s source code and executes your tests. You can configure Karma to run against a number of browsers, which is useful for being confident that your application works on all browsers you need to support. Karma is executed on the command line and will display the results of your tests on the command line once they have run in the browser.

Karma is a NodeJS application and should be installed through NPM/YARN.

Jasmine

Jasmine is a behavior-driven development framework for JavaScript that has become the most popular choice for testing Angular applications. Jasmine provides functions to help with structuring your tests and also making assertions. As your tests grow, keeping them well structured and documented is vital, and Jasmine helps achieve this.

Jasmine comes with a number of matches that help you make a variety of assertions. To use Jasmine with Karma, we use the karma-jasmine test runner.

Angular Mocks

Angular also provides the angular-mocks module, which provides mocking for your tests. This is used to inject and mock Angular services within unit tests. In addition, it is able to extend other modules so that they are in sync. Having tests in sync keeps them much cleaner and easier to work with. One of the most useful parts of angular-mock is $httpBackend, which lets us mock XHR requests in tests and return sample data instead.

Mocha

This tool runs on NodeJS and is used with browsers for asynchronous testing. A feature-rich JS framework, Mocha test runs serially mapping uncaught exceptions to correct test cases. It has a flexible and an accurate reporting.

What are Modules in Typescript?

Modules are powerful way to share code between files. By using modules effectively in your project you can keep your file size small and dependencies clear.
Modules are executed within their own scope and not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms.

Example of creating a Module:

module module_name{

	class xyz{
		export foo(x, y){
		 	return x*y;
		 }
	}

}

What are the benefits of using Typescript?

  • One of the biggest advantages of Typescript is its code completion and intelligence.
  • It provides the benefits of optional static typing .Here Typescript provides types that can be added to variables, functions, properties etc.
  • Typescript has the ability to compile down to a version of JavaScript that runs on all browsers.
  • Typescript tries to extend JavaScript. Compiler generates JavaScript.
  • Typescript is a backward compatible version of JavaScript that compiles to pure JavaScript which makes their writing easier and faster.
  • Typescript is purely object oriented programming which means it is a programming paradigm based on the concepts of objects.
  • Most important advantage is it offers a compiler that can convert to JavaScript equivalent code. And it has a concept of namespace defined by a module.

To what kind of client generated views, a router can be bound?

Router can be bound to any type of client-generated views, such as link on the page, button click, drop down selection etc.

How do you upgrade the older version of Angular to higher version?

If you want to upgrade your Angular CLI or any older version of Angular to higher version of Angular, you can easily do it.

Follow the steps given below:

First, check the older version of Angular that you are using.

Run the ng --version or ng version depending on Angular version command on the Node.js command prompt.

Now, you have to uninstall the older version of Angular by using the following command:

npm uninstall -g angular-cli // For Windows Open Powershell on Administrator Mode
sudo npm uninstall -g angular-cli // For Mac

Now, verify and clear the cache by using the following commands:

npm cache verify
npm cache clean

Now, install the latest Angular CLI by using the following command:

npm install -g @angular/cli@latest

You can now verify that you are using the correct version by using the following command:

ng --version or ng version depending on Angular version.

Why are reactive forms used in Angular?

Reactive forms have a lot of important features, for instance, they are robust, scalable, testable, reusable, etcetera. That is why they are used in applications made using Angular 8, where forms are an essential component of the application.

How to use form controls and form groups in a reactive form to handle complex forms?

To handle complex forms using reactive forms, you can create a form group for each section of the form and add form controls to each group as needed.

For example, if you have a form with multiple sections for personal information, contact information, and billing information, you can create three form groups – one for each section – and add form controls for each field within each group.

Can you explain how to implement a reactive form in Angular and its advantages over template-driven forms?

A reactive form in Angular is implemented by creating a form group and form controls and binding them to the template using the formControlName and formGroup directives.

The advantages of reactive forms over template-driven forms include greater control over form behavior, more efficient way of handling of form data, and improved form validation.

How do you validate form inputs in a reactive form and what are the different types of validation you can perform?

In a reactive form, form validation can be performed using the Validators module, which provides a variety of built-in validation functions. Some common validation functions include required, minLength, maxLength, and pattern. Custom validators can also be created for more complex validation needs.

How to reset a reactive form to its original state and clear all form controls?

To reset a reactive form to its original state and clear all form controls, you can call the form’s reset() method and pass it an object with the desired values for each form control.

For example, to reset a form with a name and email form control to its original state, you can call:

form.reset({ name: '', email: '' }).

What are the differences between pure and impure pipes and how it might affect the performance of the application?

You are working on an Angular project that involves transforming data in the view using pipes. You want to make sure that the pipes you use are performant and efficient.

In Angular, there are two types of pipes: pure and impure. A pure pipe is only re-evaluated when its inputs change, while an impure pipe is re-evaluated on every change detection cycle. Using a pure pipe is generally more efficient than using an impure pipe, as it reduces the amount of work that Angular has to do when detecting changes. This can result in a more performant application, particularly when dealing with large amounts of data. However, there are situations where an impure pipe might be more appropriate. For example, if the pipe involves an expensive calculation, or if it needs to update constantly in response to user input, an impure pipe might be the better choice. In this scenario, it’s important to weigh the trade-offs between using a pure and impure pipe, and choose the option that best meets the needs of your application.

What is Data Binding?

In order to connect application data with the DOM (Data Object Model), data binding is used. It happens between the template (HTML) and component (TypeScript). There are 3 ways to achieve data binding: Event Binding – Enables the application to respond to user input in the target environment , Property Binding – Enables interpolation of values computed from application data into the HTML, Two-way Binding – Changes made in the application state gets automatically reflected in the view and vice-versa. The ngModel directive is used for achieving this type of data binding.

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

Yes, it can be done with Angular Universal, a technology provided by Angular capable of rendering applications on the server-side.

The benefits of using Angular Universal are:

  • Better User Experience: Allows users to see the view of the application instantly.
  • Better SEO: Universal ensures that the content is available on every search engine leading to better SEO.
  • Loads Faster: Render pages are available to the browsers sooner, so the server-side application loads faster.

How to navigate between different routes in an Angular application?

You need to import the router package as shown below in the type script file:

import from "@angular/router";

Then you can use @Component to declare selectors and template.

Then use the following example code to navigate between routes:

class HeaderNavComponent {

 constructor(private router: Router) {}
 
 goHome() {
   this.router.navigate(['']); 
 }
 
 goSearch() {
   this.router.navigate([‘search’]);
 }
}

What are the life cycle events in Angular?

ngOnInit: This event basically is called only once just after the ngOnChanges() events. This event is mainly used for initializing data in a component.

ngDoCheck: This event is triggered every time when the input properties of a component are checked. You can use this hook method to implement the check with your own logic check.

ngAfterContentInit: This method executes only for the first time when all the bindings of the component need to be checked for the first time. This event executes just after the ngDoCheck() method.

ngAfterContentChecked: This lifecycle hook method executes every time when the content of the component has been checked by the change detection mechanism of the Angular. This method called after ngAfterContentInit() method. This method is also called on every subsequent execution of ngDoCheck().

ngAfterViewInit: This lifecycle hook method executes when the component’s view has been fully initialized. It is called only the first time after ngAfterContentChecked().

ngAfterViewChecked: This method is just called after the ngAterViewInit() method. It is executed every time when the view of the given component has been checked by the change detection algorithm of Angular. This method executes every subsequence execution of the ngAfterContentChecked().

ngOnDestroy: This method is very useful for unsubscribing the observables and detaching the event handlers to avoid memory leaks. This method is called only once just before the component is removed from the DOM.

How does optional chaining work in TypeScript?

Optional chaining allows you to access properties and call methods on them in a chain-like fashion. You can do this using the ?. operator. TypeScript immediately stops running some expression if it runs into a null or undefined value and returns undefined for the entire expression chain. Using optional chaining, the following expression

let z = foo === null || foo === undefined ? undefined : foo.bar.baz();

can be expressed as follows:

let z = foo?.bar.baz();

What is the diffrence between RouterModule.forRoot() vs RouterModule.forChild()?

RouterModule.forRoot() creates a module that contains all the directives, the given routes, and the router service itself.

RouterModule.forChild() creates a module that contains all the directives and the given routes, but does not include the router service. It registers the routers and uses the router service created at the root level.

This is important because location is a mutable global property. Having more than one object manipulating the location is not a good idea.