Tech Point Fundamentals

Saturday, November 18, 2023

Angular Interview Questions and Answers - Part 09

Angular Interview Questions and Answers - Part 09

Angular-Interview-Questions-And-Answers

Angular is a popular open-source single-page application design framework and development platform. It is a robust front-end JavaScript framework that is widely used for front-end application development. Nowadays Angular is very famous as frontend technology so it is very common for the interview point as well. 

Introduction


This is the Angular Interview Questions and Answers series. Here we will see 200+ Most Frequently Asked Angular Interview Questions. This is the 9th part of the Angular Interview Questions and Answer series.

I will highly recommend to please do visit the following parts before continuing to this part:


Please do visit our YouTube Channel here to watch Interview Questions & Answers and important technology videos.

In this part we will discuss the following Important Angular Interview Questions:

Q096. What are the differences between @Component vs. @NgModule vs. @Directive decorator in Angular?
Q097. What is @Inject Decorator in Angular? 
Q098. What is the difference between @Inject() vs. @Injectable() in Angular?
Q099. What is @Input Decorator in Angular?
Q100. What is @Output Decorator in Angular?
Q101. What is Content Projection in Angular? What is the use of ng-content in Angular?
Q102. What is the difference between @ContentChild vs. @ContentChildren decorators in Angular?
Q103. What is the difference between @ViewChild vs. @ViewChildren decorator in Angular?
Q104. What is the use of @HostBinding Decorator in Angular? How it is different from @HostListener?
Q105. What is @Host Decorator in Angular? What is the difference between @Host vs. @Self decorator?
Q106. What is the use of @Self Decorator in Angular?
Q107. What is the use of @SkipSelf Decorator in Angular?
Q108. What is @Optional Decorator in Angular? What is the use of @Optional Decorator in Angular?
Q109. What is the difference between @Self vs. @SkipSelf vs. @Optional decorator in Angular?

Angular Interview Questions and Answers: Part 09


Q096. What are the differences between @Component vs. @NgModule vs. @Directive decorator in Angular?

The @Component decorator is used when you want to create new elements in the DOM with their own HTML template. While the @Directive attribute directives are used when you want to change or update the existing elements in the DOM. 

A component is decorated by the @Component attribute and so a general perception is that it's different from a directive. But actually, a Component is a sophisticated directive that renders a non-existing HTML DOM onto the View, while the directives control an existing DOM.

Angular components are the major UI building blocks of an Angular application. The Angular components are the subset of Directives and the Angular components are always associated with a  template. So Angular Components have their own view whereas Angular Directives are used to add additional behavior to an existing DOM element or an existing component instance.

Directives are Angular features that can help us modify the structural or behavioral aspects of the HTML elements on which these Directives are applied. We can apply a Directive on an HTML element and from within the Directive we can access the DOM of the HTML element using which we can play around with the element, such as modifying the attributes of the element, adding behavior or even controlling the element itself. 

Q097. What is @Inject Decorator in Angular? 

In Angular, the @Inject is a Parameter decorator. The @Inject() is a constructor parameter decorator, which tells angular to Inject the parameter with the dependency provided in the given token. It is a manual way of injecting the dependency.

So @Inject() is a manual mechanism for letting Angular know that a parameter must be injected. When using TypeScript, @Inject is only needed for injecting primitives. TypeScript's types let Angular know what to do in most cases.

import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `Encryption: {{ encryption }}`
})
export class ProductService{
constructor(@Inject(LoggerService) private loggerService) {
  this.loggerService.log("Product Service Constructed");
}
}

Q098. What is the difference between @Inject() vs. @Injectable() in Angular?

Both decorators are related to DI. The @Inject is a constructor parameter decorator while @Injectable is a class decorator in Angular. We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. On the other hand, we use the @Injectable class decorators to automatically resolve and inject all the parameters of the class constructor.

This only works if each parameter has a TypeScript type associated with it, which the DI framework uses as the token. We don’t need to use the @Injectable class decorator on classes that are already decorated with one of the other Angular decorators, such as @Component.

In short @Inject() is a manual mechanism for letting Angular know that a parameter must be injected. It tells angular to Inject the parameter with the dependency provided in the given token.  When using TypeScript, @Inject is only needed for injecting primitives. The TypeScript's types let Angular know what to do in most cases.

import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `Encryption: {{ encryption }}`
})
export class ProductService{
constructor(@Inject(LoggerService) private loggerService) {
  this.loggerService.log("Product Service Constructed");
}
}

On the other hand, @Injectable() lets Angular know that a class itself can be used with the dependency injector. @Injectable() is not strictly required if the class has other Angular decorators on it or does not have any dependencies. 

Adding @Injectable is not registering the service. What is important is that any class that is going to be injected with Angular is decorated here.

import { Injectable } from '@angular/core';

@Injectable()
export class LoggerService {
  log(message:any) {
  console.log(message);
  }
}


Q099. What is @Input Decorator in Angular?

In angular there are two property decorators which are used to transform the data from one component to another component. They are used to pass the different types of data from parent to child component and child to parent component.

In Angular @Input decorator is a special property decorator that is used to pass data (property binding) from parent to child component.  @Input is a decorator to mark a property as an input. So it can receive data from the parent component. The parent component uses the property binding to bind it to a component property. Whenever the value in the parent component changes angular updates the value in the child component.

To use the @Input() decorator in a child component class, first import Input and then decorate the property with @Input(). To watch for changes on an @Input() property, use OnChanges(), one of Angular's lifecycle hooks.

import { Component, Input, OnInit } from '@angular/core';  
@Component({  
   selector: 'app-user',  
   templateUrl: './user.component.html',  
   styleUrls: ['./user.component.css']  
})      
export class UserComponent implements OnInit {  
@Input() statusMsg:string;
 
constructor() { }    
ngOnInit() {  
   console.log(this.statusMsg);  
   }      
}

Q100. What is @Output Decorator in Angular?

The @Output decorator is also a property decorator in Angular.  @Output decorator is used to pass the data from the child to the parent component. The @Output() decorator in a child component or directive lets data flow from the child to the parent. The @Output() marks a property in a child component as a doorway through which data can travel from the child to the parent.

The @Output decorator binds a property of a component, to send data from one component to the calling component. To transfer the data from the child to the parent component, we use the @Output decorator. In order to use @Output(), you must configure the parent and child.

The child component uses the @Output() property to raise an event to notify the parent for the change. To raise an event, an @Output() must have the type of EventEmitter, which is a class in @angular/core that you use to emit custom events. 

So to use the @Output decorator we have to import, two important decorators, they are Output and EventEmitter. EventEmitter is used in components with the @Output directive to emit custom events synchronously or asynchronously and register handlers for those events by subscribing to an instance. 

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';  

@Component({  
   selector: 'app-master',  
   templateUrl: './master.component.html',  
   styleUrls: ['./master.component.css']  
})  
export class MasterComponent implements OnInit {  
   @Input() myinputMsg:string;  
   @Output() myOutput:EventEmitter<string>= new EventEmitter();  
   outputMessage:string="I am child component."  
   constructor() { }    
   ngOnInit() {  
    console.log(this.myinputMsg);  
   }  
}

Q101. What is Content Projection in Angular? What is the use of ng-content in Angular?

Content projection is a pattern in which you insert or project, the content you want to use inside another component. So we use content projection to create flexible, reusable components in Angular. Content projection is a way to pass the HTML content from the parent component to the child component. The child component will display the template in a designated spot.

There are multiple implementations of content projection in Angular like Single-slot content projection, Multi-slot content projection, or Conditional content projection.

In Single-slot content projection, a component accepts content from a single source. In Multi-slot content projection, a component accepts content from multiple sources. Components that use conditional content projection render content only when specific conditions are met.

We use <ng-content> element where we want the projected content to appear in the HTML template of the component. The ng-content acts as a placeholder. With the <ng-content> element in place, users of this component can now project their own message into the component. The <ng-content> element is a placeholder that does not create a real DOM element. Custom attributes applied to <ng-content> are ignored.

import { Component } from '@angular/core';

@Component({
  selector: 'app-projection-demo',
  template: `<h2>Single-slot content projection</h2>
      <ng-content></ng-content>`
})
export class ProjectionDemoComponent {}

With the <ng-content> element in place, users of this component can now project their own message into the component.

<app-projection-demo>
    <p>Content projection is very cool</p>
</app-projection-demo>

Q102. What is the difference between @ContentChild vs @ContentChildren decorators in Angular?

On a high level, @ContentChild and @ContentChildren are property decorators. They are used to query or help to get a reference to the projected content. 

Both @ContentChild and @ContentChildren decorators are used to fetch single child elements or all child elements from the content DOM. The ContentChild & ContentChildren is very similar to the ViewChild & ViewChildren.

@ContentChild Decorator:

The @ContentChild gives the first element matching the selector from the content DOM while @ContentChildren gives all elements of the content DOM as QueryList. Contents queried by @ContentChild and @ContentChildren are set before ngAfterContentInit() is called. 

If we perform any change in the content DOM for the matching selector, that will be observed by @ContentChild and @ContentChildren and we will get the updated value. As a selector for @ContentChild and @ContentChildren, we can pass directive, component, or local template variable.

@ContentChildren Decorator:

By default, @ContentChildren only selects direct children of content DOM and not all descendants. The metadata of @ContentChildren is descendants and by setting its value true, we can fetch all descendant elements.

@ContentChild gives the first element or directive matching the selector from the content DOM. If the new child element replaces the old one by matching the selector in the content DOM, then the property will also be updated. 

On the other hand, @ContentChildren is used to get QueryList of elements or directives from the content DOM. When there is a change in content DOM, data in QueryList will also change. If child elements are added, we will get those new elements in QueryList. If child elements are removed, then those elements will be removed from the QueryList as well. 

AfterContentInit() is a lifecycle hook that is called after directive content is fully initialized. It has a method ngAfterContentInit() that runs after angular loads external content into the component view. This method runs once after the first ngDoCheck() method. Contents queried by @ContentChild and @ContentChildren are set before ngAfterContentInit() is called. 

Q103. What is the difference between @ViewChild vs. @ViewChildren Decorator in Angular?

Both @ViewChild and @ViewChildren are parameter decorators in Angular. ViewChild returns the first matching element and ViewChildren returns all the matching elements as QueryList of items. We can use these references to manipulate element properties in the component.

We use the ViewChild or ViewChildren to Query and get the reference of any DOM element in the Component. The DOM element can be an HTML element, Child Component, Directive, etc. However, we cannot use the ViewChild or  ViewChildren to get the reference to the template inserted using the Content projection.

@ViewChild Decorator:

A @ViewChild decorator is used to get the reference of the DOM element rendered inside an Angular component. We can use the reference of the DOM element to manipulate element properties. To get the component, we need to specify a selector. @ViewChild using JavaScript, we can use a selector to extract the component. 

The ViewChild query always returns the first matching element from the DOM and updates the component variable on which we apply it. We apply the viewChild decorator on a Component Property. It takes two arguments: - selector and opts. 

ViewChild returning undefined is one of the common errors, we encounter when we use them. This error is because we try to use the value before the ViewChild initializes it. Angular raises the AfterViewInit life cycle hook once it completes the View Initialization. So we can use the ngAfterViewInit to access the child variable.

@ViewChildren Decorator:

Working with @ViewChildren is similar to @ViewChild, but the difference between the two is that @ViewChildren provides a list of element references rather than returning a single reference. It is used to reference multiple elements. 

ViewChildren decorator is used to get the list of element references from the View. ViewChildren is different from the ViewChild. ViewChild always returns the reference to a single element. If there are multiple elements the ViewChild returns the first matching element, but ViewChildren always returns all the elements as a QueryList. You can iterate through the list and access each element.

The QueryList is the return type of both ViewChildren and contentChildren. QueryList stores the items returned by the viewChildren or contentChildren in a list. Angular updates this list, whenever the state of the application change. It does it on each change detection.

The ViewChildren is always resolved after the change detection is run. i.e. why it does not have a static option. And also you cannot refer to it in the ngOnInit hook as it is yet to initialize. 

Q104. What is the use of @HostBinding Decorator in Angular? How it is different from @HostListener?

Both HostBinding & HostListener are method decorators in Angular. HostListener listens to host events, while HostBinding allows us to bind to a property of the host element. The host is an element to which we attach our component or directive. This feature allows us to manipulate the host styles or take some action whenever the user performs some action on the host element.

@HostBinding() function decorator allows you to set the properties of the host element from the directive class.

import { Directive, HostBinding } from '@angular/core';
@Directive({
  selector: '[appRainbow]'
})
export class RainbowDirective {
 @HostBinding('style.color') color!: string;
}

HostListener is a method decorator that listens to the DOM event on the host element. It also provides a handler method to run when that event occurs.

@HostListener('click') onClick() {
  window.alert('Host Element Clicked');
}

Q105. What is @Host Decorator in Angular? What is the difference between @Host vs. @Self decorator?

In Angular @Host is a parameter decorator which is one of the Resolution Modifiers in Angular. The Host decorator tells the Angular DI framework to resolve the dependency in the view by checking injectors of child elements and stopping when reaching the host element of the current component.

The @Host property searches for the dependency inside the component’s template only. It starts with the current Injector and continues to search in the Injector hierarchy until it reaches the host element of the current component. It does not search for the dependency in the Providers of the host element. But it does search in the ViewProviders of the host element. Also, the Module injector is never searched in the case of the @Host flag.

@Host looks somewhat similar to @Self but there is a key difference between them. A @Self decorator only checks in the Injector of the current component while @Host checks for the dependency in the current template.

@Component({
  selector: "my-child",
  providers: [],
  viewProviders: [],
  template: `
  <div class="box">
    <p>ChildComponent => {{ age }}</p>  
    <my-grandChild></my-grandChild>
  </div>`
})
export class ChildComponent {}


Now in ChildComponent, we can add the @Host decorator:

export class GrandChildComponent {
  age;
  constructor(@Host() private myService: MyService) {
  this.age = myService?.age;
  }
}

Q106. What is the use of @Self Decorator in Angular?

The @Self decorator instructs Angular to look for the dependency only in the local injector. The local injector is the injector that is part of the current component or directive. This forces the Angular DI Framework to look for the Dependency attached to the current Component. 

Self-decorator causes Angular to look for the dependency only locally i.e. in the providers’ array in the component or directive where the service is injected. If the array is empty and we declare to use the service in the constructor, we get an error i.e. NullInjectorError. Otherwise, the component will use the service that was injected in the constructor.

import { Component, Self } from '@angular/core';

@Component({
  selector: 'app-profile',
  template: '...',
  providers: [{ provide: ProfileService }]
})
export class ProfileComponent {
  constructor(@Self() public profileService: ProfileService) {}
}

Q107. What is the use of @SkipSelf Decorator in Angular?

The @SkipSelf decorator instructs Angular explicitly to look for the dependency in the Parent Injector and upwards. It tells Angular not to look for the injector in the local injector, but to start from the Parent. You can think of this decorator as the opposite of the @Self.

SkipSelf decorator causes Angular to look for dependencies in the parent component or beyond in the provider's array in these components. If the provider's array in the parent component is empty and we declare to use the service in the child component constructor, we will get a NullInjectorError error. Otherwise, the component will use the service that was injected in the constructor of the parent component or a further component.

import { Component, SkipSelf } from '@angular/core';

@Component({
  selector: 'app-child',
  template: '...'
})
export class ChildComponent {
  constructor(@SkipSelf() public loggingService: LoggingService) {}
}

Q108. What is @Optional Decorator in Angular? What is the use of @Optional Decorator in Angular?

In Angular to indicate that a dependency is optional, we can use the @Optional decorator.  @Optional marks the dependency as Optional. If the dependency service is not found, then it returns null instead of throwing an error.

If you add the @Optional decorator along with the @Self. Now, the dependency injection will return null instead of an error. Also, you need to add the null check (?) in service, or else you will get the “Cannot read property of "null" error.

In the case of @Optional, a Null will be injected as a dependency if the dependency cannot be located in the injector hierarchy. The @Optional decorator is useful when you want to specify that a dependency is not required for a component to function properly. It can also be useful when you want to test a component in isolation and need to provide mock dependencies.

@Component({
  selector: 'app-example',
  template: '...'
})
export class ExampleComponent {
  constructor(@Optional() public myService: MyService) {}
}

Q109. What is the difference between @Self vs. @SkipSelf vs. @Optional Decorator in Angular?

All @Self, @SkipSelf, @Optional & @Host are Angular Decorators that configure how the DI Framework should resolve the dependencies.  These decorators are called Resolution Modifiers because they modify the behavior of injectors. These Decorators configure how the DI Framework resolves the dependencies.

The @Self decorator instructs Angular to look for the dependency only in the local injector i.e. providers’ array in the component or directive where the service is injected. If the array is empty and we declare to use the service in the constructor, we get an error i.e. NullInjectorError

The @SkipSelf decorator instructs Angular to look for the dependency in the Parent Injector and upwards. If the provider's array in the parent component is empty and we declare to use the service in the child component constructor, we will get a NullInjectorError error.

The @Optional decorator marks the dependency as Optional. If the dependency service is not found, then it returns null instead of throwing an error. Null will be injected as a dependency if the dependency cannot be located in the injector hierarchy.


Recommended Articles




Thanks for visiting this page. Please follow and join us on  LinkedInFacebookTelegramQuoraYouTubeTwitterInstagramWhatsApp, VKTumbler, and Pinterest for regular updates.

No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.