interview

Angular Interview Questions & Answers

💡 What is property binding and attribute binding?

Property binding in Angular helps you set values for properties of HTML elements or directives.
In this example, src is the name of the element property.

<img [src]="itemImageUrl">

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.
It is recommended that you set an element property with a property binding whenever possible.

Attribute binding uses the prefix attr, followed by a dot. and sets the attribute value with an expression that resolves to a string. When the expression resolves to null or undefined, Angular removes the attribute altogether.

<p [attr.attribute-you-are-targeting]="expression"></p>


💡 What is the difference between the below two lines Code?

<input [disabled]="condition ? true : false">

<input [attr.disabled]="condition ? 'disabled' : null">

The first one is property binding and the second is attribute binding.
The first line, which uses the disabled property, uses a boolean value. The second line, which uses the disabled attribute checks for null.


💡 How many types of binding, Angular provides?

Angular provides three categories of data binding according to the direction of data flow.

  • One-way from data source to view target also known as Property binding -> Use [] to bind from source to view.
  • One-way from view target to data source also known as Event Binding – Use () to bind from view to the source.
  • Two-way Binding –> Use [()] to bind in a two-way sequence.


💡 What is a template variable and how we declare that?

To declare a template variable, We use the hash symbol #. We can then refer to this template variable anywhere in the component’s template to use data from one part of a template in another part of the template.

<input #phone placeholder="phone number" />

<!-- phone refers to the input element; pass its `value` to an event handler -->
<button (click)="callPhone(phone.value)">Call</button>


💡 What is the difference between Subject and BehaviorSubject?

  • A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A subject doesn’t hold value.
  • BehaviorSubject keeps in memory the last value that was emitted by the observable. A regular Subject doesn’t.
const subject = new Rx.Subject();
subject.next(1);
subject.subscribe(x => console.log(x));

Console output will be empty
const subject = new Rx.BehaviorSubject(0);
subject.next(1);
subject.subscribe(x => console.log(x));

Console output: 1

BehaviorSubject should be created with an initial value: new Rx.BehaviorSubject(1).
Consider ReplaySubject if you want the subject to hold more than one value.

Angular Interview Questions & Answers


💡 Explain View Encapsulations and their types?

ViewEncapsulation.Emulated – This is the default. Style will be scoped to the component. Angular will not create a Shadow DOM for the component. Parent Component’s styles will not be applied to its child components.

✔ ViewEncapsulation.Native – Angular creates a Shadow DOM and the style is scoped to that Shadow DOM. Child Component can also access Parent Component styles.

✔ ViewEncapsulation.None
There is no shadow dom here. Style is not scoped to the component and Styles are available to all components.


💡 What is the life cycle of Angular Element (Custom Element)?

class MyElement extends HTMLElement {
}

A custom element can define special lifecycle hooks for running code during interesting times of its existence. These are called custom element reactions.

✔️ constructor — An instance of the element is created or upgraded
✔️ connectedCallback — Called every time the element is inserted into the DOM
✔️ disconnectedCallback — Called every time the element is removed from the DOM. Useful for running clean-up code.
✔️ attributeChangedCallback — Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial values when an element is created by the parser or upgraded.
✔️ adoptedCallback — The custom element has been moved into a new document.


💡 How to implement Error handling in the Angular app?

HttpInterceptor provides a way to transform HTTP request before sending to the server and to handle response before sending them to the application. We can add or modify HTTP headers, can pass authentication tokens.
We can also handle responses and errors coming from the server.

Global error handling is done by the HTTP Interceptor concept. Let’s see the below code.

💻 We create a HttpErrorInterceptor that implements HttpInterceptor and its intercept method. Below is the sample code of Interceptor.

export class HttpErrorInterceptor implements HttpInterceptor {
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return next.handle(request)
     .pipe(
       retry(1),
       catchError((error: HttpErrorResponse) => {
         let errorMessage = '';
         if (error.error instanceof ErrorEvent) {
           // client-side error
           errorMessage = `Error: ${error.error.message}`;
         } else {
           // server-side error
           errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
         }
         window.alert(errorMessage);
         return throwError(errorMessage);
       })
     )
 }
}
// Define in app.module file: 
providers: [
   {
     provide: HTTP_INTERCEPTORS,
     useClass: HttpErrorInterceptor,
     multi: true
   }
 ]

Angular Interview Questions & Answers


💡 How many types of Angular Decorators?

Angular has 4 types of built-In decorators

Class decorators, e.g. @Component, @Injectable, @Directive, @pipe and @NgModule
Property decorators for properties inside classes, e.g. @Input and @Output
Method decorators for methods inside classes, e.g. @HostListener
Parameter decorators for parameters inside class constructors, e.g. @Inject


💡 How to create a Custome Decorator?

Decorators are actually just functions, it’s as simple as that, and are called with whatever they are decorating.

function Console(message) {
  // access the "metadata" message
  console.log(message);
  // return a function closure, which is passed the class as `target`
  return function(target) {
    console.log('Our decorated class', target);
  };
}nmn

***** Use ******

@Console('Hey!')
class ExampleClass {
  constructor() {
    console.log('Yo!');
  }
}


💡 What are the differences between (change) vs (ngModelChange) in angular?

First we need to understand that change is not an “Angular event”, it’s a DOM event that will give us exactly what we’d expect in “plain JavaScript DOM”.
Whereas ngModelChange is an Angular event. It fires when ngModel changes. we can’t use (ngModelChange) without ngModel Whereas the (change) event can be used anywhere.

// ngModelChange event 
<input [ngModel]="bar" (ngModelChange)="modelChangeFn($event)"> 

 --->above line of code same as  <input [(ngModel)]="bar">

// Change event   
 <input [value]="foo" (change)="changeFn($event)">


💡 What are the differences between ng-pristine and ng-dirty angular classes?

The form controls start in a pristine state, meaning that the data has not yet been modified by the user. The control will then get applied the CSS class ng-pristine.
Once the user modifies the form data, the form control is dirty, and the ng-dirty CSS class gets applied by Angular, and the ng-pristine class gets removed.


💡 What is Change Detection Strategy?

ChangeDetectionStrategy.Default

It will perform checks every time something may have changed, this is called dirty checking and for each browser events, timers, XHRs, and promises.

ChangeDetectionStrategy.OnPush

It will rely only on the change of the Input references, some events triggered by itself (the component), or one of its children. This has for effect to gain a lot on performance.

The change detection strategy will kick in when:

  • The Input reference changes;
  • An event originated from the component or one of its children;
  • Run change detection explicitly (componentRef.markForCheck());
  • Use the async pipe in the view.


💡 How to use HttpClient with async/await?

private async fetchData(){
    const data = await this.httpClient.get(this.apiUrl).toPromise();
    console.log("Data: " + JSON.stringify(data)); 
  }


💡 What is Server-Side Rendering (SSR)? What is Angular Universal?

An Angular application is a Single-page App – it runs in a client’s browser. But we can run the angular app through the server by using Angular Universal. SSR enables you to serve static HTML to the client.
With Angular Universal, the server will pre-render pages and show users something, while the client-side app loads in the background. Then, once everything is ready client-side, it will seamlessly switch from showing the server-rendered pages to the client-side app.

To enable SSR in the angular app we use-package: @nguniversal/express-engine

$ ng add @nguniversal/express-engine --clientProject {{ name of your project }}

Run commands: $ npm run build:ssr && npm run serve:ssr


💡 Why Reactive Form much preferable compare to template-driven form?

In template-driven form, HTML file contains all source code and all the form validation rules and that is something that can become pretty hard to read and maintain very quickly. And It becomes tough to cross-validate fields by using custom validators. Due to the big template file, the readability and maintainability of the form decrease.
Another is form validation logic cannot be easily unit tested and the templates can become complex rather quickly.

Reactive Form:

we imported ReactiveFormsModule instead of FormsModule.

import {ReactiveFormsModule} from "@angular/forms";

// Other module which we use for reactive form inside Component:

import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
  • The HTML template is a lot cleaner and focuses only on presentation logic.
  • All the business validation rules are written in component class, where they can be unit tested a lot more easily.
  • Moving the form model definition to the component makes it very easy to define the form dynamically if necessary.
  • Also, with reactive forms, it’s a lot easier to create a custom validator.


💡 But why are they called reactive forms?

These types of forms are called Reactive Forms because the individual form controls and also the form itself provide an Observable-based API.
This means that both the controls and the whole form itself can be viewed as a continuous stream of values, that can be subscribed to and processed using commonly used RxJs operators.


💡 What is the purpose of FormBuilder service in Reactive Form?

In the case of larger forms, creating form models by explicitly calling the FormGroup and FormControl constructors can become hard.
Instead of calling the FormGroup and FormControl constructors directly, we can use a simplified array notation for defining the form model that is FormBuilder.

// Creating Form with Form Group 
form = new FormGroup({
            "firstName": new FormControl("", Validators.required),
            "password": new FormControl("", Validators.required),
    });

// Creating Form with FormBuilder
  form = fb.group({
            "firstName": ["", Validators.required],
            "password":["", Validators.required]
        });
   
  constructor(fb: FormBuilder) {
  }


💡 What is difference between patchValue() and setValue() method?

patchValue() – This method does not need to receive values for all fields of the form, so we can use it to update only a few fields at a time.
setValue() – In the case of this method, values for all form fields will need to be provided, otherwise, we will get an error message saying that some fields are missing.


💡 How to use Query Parameters with Router.navigate?

this.router.navigate(['/products'], { queryParams: { order: 'popular' } });

URL: http://localhost:4200/products?order=popular

You can also provide multiple query parameters.

this.router.navigate(['/phones'], { queryParams: { model: 'samsung', color: 'white' } });

URL: http://localhost:4200/phones?model=samsung&color=white


💡 How to pass Query Parameters with RouterLink?

 <a [routerLink]="['/employee']" [queryParams]="{ name: 'jsmount'}">
  Employees
</a>


💡 What are the differences between router.navigate and router.navigateByUrl?

this.router.navigateByUrl(`/student/${student.id}`);

this.router.navigate(['/student', student.id]);

Using router.navigateByUrl, we provide a whole new URL, which is similar to changing the location bar directly.
Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

To see the difference clearly, imagine that the current URL is ‘/inbox/11/messages/22(popup:compose)’

  • With this URL, calling router.navigateByUrl(‘/inbox/33/messages/44’) will result in ‘/inbox/33/messages/44’.
  • But calling it with router.navigate([‘/inbox/33/messages/44’]) will result in ‘/inbox/33/messages/44(popup:compose)’.


💡 What is router-outlet?

The Router-Outlet is a directive that’s available from the router library. Router Module inserts the component that gets matched based on the current browser’s URL. You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios.


💡 What are the available values of pathMatch in Router?

prefix – It is the default.
full – The second matching strategy is full. The router will check if the path is exactly equal to the path of the current browser’s URL.


💡 What are AUXILIARY ROUTES?

A component has one associated primary route and can have auxiliary routes. Auxiliary routes enable developers to navigate multiple routes at the same time.
To create an auxiliary route, you’ll need a named router outlet where the component associated with the auxiliary route will be displayed.

<router-outlet></router-outlet>  --- primary
 ---> auxiliary
<router-outlet  name="contactOutlet"></router-outlet> 

use: { path: "contacts", component: ContactListComponent, outlet: "contactOutlet" }


💡 How can we activate children’s routes (more than one route) at the same time on the same page?

Let’s display EmployeeList and EmployeeInfo on the same page using auxiliary routes on Employee Component.

**Route Structure ** 

 { path: 'employee', component: EmployeeComponent,
    children: [
     { path: 'employeeList', component: EmployeeListComponent, outlet: 'list' },
     { path: ':id', component: EmployeeInfoComponent, outlet: 'info' }
    ] 
  }

EmployeeComponent: In the first outlet, we want to insert EmployeeList and on the second outlet, we want to insert EmployeeInfo Component respectively.

**EmployeeComponent**

<div class="main">
    <div>
     <router-outlet name="list"></router-outlet>
    </div>
    <div>
     <router-outlet name="info"></router-outlet>
    </div>
   </div>

Navigate to Employee Component with employeeList route to be rendered in the first outlet:

 [routerLink]="['/employee', {outlets: {'list': ['employeeList'], 'info': ['none']}}]">

When clicking on an employee list item, It should show Employee Info right side on the same page.

// add click event on list item and add routing
showEmployeeInfo(id) {
    this.router.navigate(['/employee', {outlets: {'info': [id]}}]);
  }

Now get this Id in EmployeeInfo Component by using ActivatedRoute –

  ngOnInit() {
  this.route.params.subscribe((params: {id: string}) => {
    // Now based on this Id -you can display employee information
    this.currentEmployee = parem.id;
  });

URL will be like : http://localhost:4200/employee/(info:1//list:employeeList)


💡 How to reload the Current active route in Angular 5+?

In Angular, there is no method like route.reload() as we had in Angular JS.
Before Angular 5, the Developer uses a hack to implement this to route A > B > A. Means route to another Component and then back to navigate the original route.
As of Angular 5.1, there is a supported technique for route reloading. This can now be done using the onSameUrlNavigation configuration option. Values of onSameUrlNavigation ’reload’ or false. The default value is false, causing nothing to happen when the router is asked to navigate to the active route.

Two major changes required to configure the route for the reloading technique.

// add onSameUrlNavigation config in imports section 

imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})]

// With Route Object, pass runGuardsAndResolvers property
{
   path: ‘orders’,
   component: OrderComponent,
   runGuardsAndResolvers: ‘always’,
}

Component Code >

constructor(private router: Router) {}

this.router.events.subscribe((e: any) => {
     // If it is a NavigationEnd event re-initalise the component
     if (e instanceof NavigationEnd) {
        // Set default values and re-fetch any data you need.
     }
   });
 }

Angular Interview Questions & Answers


💡 What is Route Guard?

Before Router navigation, Angular allows running some logic when a route is requested, and based on that it allows or denies that route. It’s commonly used to check if a user is logged in and has the authorization before he can access a page.

{ path:  'contacts/:id, canActivate:[MyGuard], component:  ContactDetailComponent}


💡 What is canDeactivate guard and what is the purpose of it?

CanDeactivate is an interface that is implemented by a class to create a guard which decides if a route can be deactivated.
CanDeactivate guard can be used in the scenario, for example, suppose a user is changing form data and before saving, User tries to navigate away. In this scenario, we can use CanDeactivate guard which will deactivate the route and open a Dialog Box to take user confirmation.

✔ How to use:

To use CanDeactivate in our application, we need to create a service decorated with @Injectable() and implements by CanDeactivate and have a canDeactivate() method. If a component needs CanDeactivate route guard then that component has also to create a method named as canDeactivate().

// Pass canDeactivate property in router config.

 {
      path: ':id',
      component: InventoryEditComponent,
      canDeactivate: [CanDeactivateGuard]
 }

 // Add canDeactivate inside component.
 
 export class InventoryEditComponent implements OnInit {  
constructor( public dialogService: DialogService) { }
canDeactivate(): Observable<boolean> | boolean {
    if (this.form.dirty) {
       return this.dialogService.confirm('Are you sure, you want to 
       discard changes?');
    }
    return true;
}	
} 

✔ Angular Interview Question & Answers for Experienced – Part 1

✔ Web Application Security Best Practices | Top Tips to Secure Angular App

✔ What’s new in Angular 9 | Top updates in Angular 9 By JS mount

✔ What’s new in Angular 8 | Angular 8 Latest Feature By JS mount

✔ Best Practices for Writing Angular Apps | Angular Guidelines

✔ NgRx Top Interview Questions and Answers You should know

✔ Tips to Boost Angular App Performance | Web page Speed Optimization

✔ Angular NgModule, AOT, and DI, and EntryComponents with example

✔ Angular Dependency Injection Provider and Types of Provider

✔ Rx JS Top Operators with examples | Rx JS interview questions

✔ Prime NG Row Group with Subheader and Totals Row

✔ How to implement Reactive Form with Prime NG table

✔ Angular Auto Tab Directive : Auto focus on next field

✔ Dynamic Tooltip with Angular Pipe: Performance Orientation

✔ Angular Create a Custom directive to match password and confirm password

You can read more here:
https://onehungrymind.com/named-router-outlets-in-angular-2/

Angular Interview Questions & Answers

Leave a Reply

Your email address will not be published.