Tech Point Fundamentals

Saturday, November 11, 2023

Angular Interview Questions and Answers - Part 08

Angular Interview Questions and Answers - Part 08

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 common as frontend technology so it is most 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 8th part of the Angular Interview Questions and Answer series.

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


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

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

Q084. What is the difference between Annotations vs. Decorators in Angular?
Q085. What are the different types of Decorators in Angular?
Q086. What are Class Decorators in Angular? What are the different types of class decorators in Angular?
Q087. What are Method Decorators? What are the different types of method decorators in Angular?
Q088. What are Property Decorators or Field Decorators? What are the different types of property decorators in Angular?
Q089. What is the difference between @HostBinding vs @HostListener decorators in Angular?
Q090. What are Parameter Decorators in Angular? What are the different types of parameter decorators in Angular?
Q091. What is @NgModule Decorator in Angular?
Q092. What is @Component Decorator in Angular?
Q093. What is @Injectable Decorator in Angular?
Q094. What is @Directive Decorator in Angular?
Q095. What is @Pipe Decorator in Angular?


Angular Interview Questions and Answers: Part 08


Q084. What is the difference between Annotations vs. Decorators in Angular?

Both AtScript Annotations and Decorators look like the same thing from a consumer perspective as we have exactly the same syntax. Although the syntax is identical, they are not the same. The only thing that differs is that we do not have control over how AtScript annotations are added as metadata to our code. 

Whereas decorators are rather an interface to build something that ends up as annotation. Over the long term, however, we can just focus on decorators, since those are a real proposed standard. AtScript is deprecated, and TypeScript implements decorators.

Annotations and decorators are two competing and incompatible ways to handle and compile the @ symbols that we often see attached to Angular components. Annotations create an "annotations" array. Decorators are functions that receive the decorated object and can make any changes to it they like. Traceur gives us annotations while TypeScript gives us decorators. But Angular supports both.

Although Annotations and Decorators both share the same @ symbol in Angular, they both have different language features. Nowadays AngularJs switched from AtScript to TypeScript but Annotations are also supported these days.  This is a legacy thing because Angular 2 swapped from AtScript to TypeScript. Decorators are the default in Angular but you can use Annotations too.

There is a very significant difference between Annotations and Decorators in Angular. The main difference you will notice is your imports. Because annotations and decorators are different, you will need to import different objects.

If you are using decorators, your imports will look like normal TypeScript imports:

import {Component, View} from 'angular2/angular2';

If you are using annotations then you will have to import the annotation version of the core angular components:

import {ComponentAnnotation as Component, ViewAnnotation as View} from 'angular2/angular2';

Otherwise, your Angular code will remain unchanged. Decorators are the default, and the most fun, but also offer more flexibility, and therefore more scope for screw-ups.

Annotation vs. Decorator:

  1. Annotations are hard-coded but Decorators are not hard-coded.
  2. Annotation was used by the Traceur compiler while Decorators were used by the Typescript compiler.
  3. Annotations are only metadata set on the class using the Reflect Metadata library. But the Decorator corresponds to a function that is called on the class.
  4. Annotations are used for creating attribute annotations that store arrays. A decorator is a function that gets the object that needs to be decorated.

Q085. What are the different types of Decorators in Angular?

Angular supports four types of inbuilt decorators along with user-defined custom decorators:

  1. Class Decorators
  2. Property Decorators
  3. Method Decorators
  4. Parameter Decorators
  5. Custom Decorators

There are four types of decorators and each type further has its own subset of decorators.  Each decorator starts with the @ symbol and is added before the class, method, property, or passed as a parameter. All functions have both open and closed brackets.

Q086. What are Class Decorators in Angular? What are the different types of class decorators in Angular? 

Class Decorators are the most common highest-level decorators that determine the purpose of the classes. Class decorators tell Angular that a specific class is a component or module and it is only the decorator that enables us to declare this effect without having to write any code within the class.

Class decorators are applied to a class declaration. They are used to modify the behavior of the class or add additional functionality. Class decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the class declaration. They can be used for various purposes, such as adding metadata, applying mixins, or extending the functionality of a class.

Types of Class Decorators:

  1. @Component() Decorator
  2. @Directive() Decorator
  3. @Pipe() Decorator
  4. @Injectable() Decorator
  5. @NgModule() Decorator

For Example:

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

@NgModule({  
  imports: [],  
  declarations: [],  
})  
export class ClassModule {  
  constructor() {  
  console.log('This is a class module!');  
  }  
}

Q087. What are Method Decorators? What are the different types of method decorators in Angular?

Method decorators are decorators that can be applied to angular methods within a class. They are used to modify the behavior or add additional functionality to the methods defined within our class.

The Method decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the method declaration. They can be used for tasks like logging, caching, or modifying the method's behavior based on specific conditions.

@HostListener Decorator: 

@HostListener is a method decorator that listens to host events. Hostlistener is a decorator that declares a DOM event to listen for and provides a handler method to run when that event occurs. 

Angular invokes the supplied handler method when the host element emits the specified event and updates the bound element with the result.

The host is an element to which we attach our component or directive. Using HostListener we can respond whenever the user performs some action on the host element.

import { Directive, HostListener } from '@angular/core';
@Directive({
  selector: '[appSubtitle]'
})
export class SubtitleDirective {
@HostListener('mouseenter') onMouseEnter() {
    alert("You just just hovered over the paragraph");
  }
}

Q088. What are Property Decorators or Field Decorators? What are the different types of property decorators in Angular?

Property decorators are decorators that can be applied to class properties which enables us to enhance some of the properties in our classes. The property/field decorators are the statements declared immediately before a property/field in a class definition that defines the type of that field. 

They are used to modify the behavior of the property or add additional functionality. Property decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the property declaration. They can be used for tasks like validation, memoization, or accessing metadata associated with the property.

Types of Property Decorators:

  1. @Input Decorator
  2. @Output Decorator
  3. @ContentChild & @ContentChildren Decorator
  4. @ViewChild & @ViewChildren Decorator
  5. @HostBinding Decorator

For example @HostBinding Decorator:

import { Directive, HostBinding, OnInit } from '@angular/core'
@Directive({
  selector: '[appHighLight]',
})
export class HighLightDirective implements OnInit {  
  @HostBinding('style.border')
  border: string = "";  
  ngOnInit() {
  this.border="5px solid blue"
  }
}

Q089. What is the difference between @HostBinding and @HostListener decorators in Angular?

Both HostBinding & HostListener are decorators in Angular where @HostListener is a method decorator while @HostBinding is a property decorator. 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.

The host element is the element to which we attach our directive or component. We know that components are nothing but directives with a template. So we can make use of both HostBinding & HostListner in components also. HostBinding binds a Host element property to a variable in the directive or component. Attaching a class to the host element is one of the common use cases of the HostBinding decorator. 

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


import { Directive, HostBinding, OnInit, HostListener } from '@angular/core'
@Directive({
  selector: '[appHighLight]',
})
export class HighLightDirective implements OnInit {  
  @HostBinding('style.border')
  border: string = "";
  ngOnInit() {
  }
  @HostListener('mouseover')
  onMouseOver() {
  this.border = '8px solid red';
  console.log("Mouse hover")
  }
  @HostListener('mouseleave')
  onMouseLeave() {
  this.border = '';
  console.log("Mouse Leave")
  }
}


Q090. What are Parameter Decorators in Angular? What are the different types of parameter decorators in Angular?

Parameter decorators are used to decorate the parameters of class constructors. The arguments of class constructors are decorated using parameter decorators. At runtime, every parameter decorator function is called.

Types of Parameter Decorators:

  1. @Inject Decorator
  2. @Host Decorator
  3. @Self Decorator
  4. @SkipSelf Decorator
  5. @Optional Decorator

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.

For example @Inject Decorator:

import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';

@Component({
  selector: 'my-component',
  template: '<div>Parameter decorator</div>'
})
export class MyComponent {
  constructor(@Inject(MyService) myService) {
    console.log(myService);
  }
}

Q091. What is @NgModule Decorator in Angular?

@NgModule is a Class Decorator that defines the class as an Angular Module and adds the required metadata to it. NgModules helps organize an application into cohesive blocks of functionality.

A NgModule is a class marked by the @NgModule decorator. @NgModule takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. 

It identifies the module's own components, directives, and pipes, making some of them public, through the exports property, so that external components can use them. The @NgModule can also add service providers to the application dependency injectors.

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

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Q092. What is @Component Decorator in Angular?

A Component decorator is a class decorator that allows you to mark a class as an Angular component and add additional metadata that determines how the component should be processed, instantiated, and used at runtime. Whenever you want to make a class as a component, then you need to decorate that class with @Component decorator. The decorator must come before the class definition. 

Components are the most basic building block of a UI in an Angular application. A component must belong to a NgModule in order for it to be usable by another component or application. A TypeScript class is used to create components. The Angular recognizes the class as an Angular Component only if we decorate it with the @Component Decorator.

The metadata object that gets accepted by the @Component decorator provides properties like templateUrl, selector, and others, where the template URL property points to an HTML file defining what you see on the application. 

import {Component} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Example component';
}

Q093. What is @Injectable Decorator in Angular?

In Angular @Injectable is a class decorator. When a class is decorated with @Injectable, Angular creates and manages instances of that class, resolving its dependencies as needed. When a class is marked with the @Injectable decorator, it becomes eligible for constructor injection. Constructor injection is a form of dependency injection where the dependencies of a class are provided through its constructor parameters.

Dependency injection is the core part of the Angular framework that provides components with access to services and other resources. Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service.

To use this we need to import the Injectable decorator from the @angular/core module. We can then register the service at different levels like component level, module level, and root level. To register the service at the root level, specify 'root' as the value for the providedIn property of @Injectable. The root level is the default when you create any service by Angular CLI: ng generate service service-name

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() {
  console.log('MyService instance is created!');
  }
  getMessage(): string {
  return 'Hello, Welcome to Angular World!';
  }
}

Now, you can use this service in any component or module of the application. Just import the service in the component.ts file and include it in the constructor of the component or service where you want to use it.

import { MyService } from './my-service.service';
@Component({
  selector: 'app-root',
  template: `<h2>{{ message }}</h2>`
})
export class AppComponent {
  message: string;
  constructor(private myService: MyService) {
  this.message = this.myService.getMessage();
  }
}

Q094. What is @Directive Decorator in Angular? What are the different types of directives in Angular?

In angular @Directive is a class decorator. The @Directive Decorator marks a class as an Angular directive. The directives help us to change the appearance, behavior, or layout of a DOM element.

We can create directives by annotating a class with the @Directive decorator. Angular Directive is a TypeScript class that is declared as a @Directive decorator. The directives allow you to attach behavior to DOM elements and the @Directive decorator provides you an additional metadata that determines how directives should be processed, instantiated, and used at run-time.

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

@Directive({
  selector:"[csCardHover]"
})
class CardHoverDirective { }

Types of Angular Directives:

Angular has three main types of directive:

  1. Components Directives (Directives with a template)
  2. Structural Directives
  3. Attribute Directives

Q095. What is @Pipe Decorator in Angular?

@Pipe is a class decorator in Angular. We use the @Pipe annotation to declare that a given class is a pipe. Pipes transform displayed values within a template. A pipe class must also implement a PipeTransform interface.

The @Pipe decorator allows you to define the pipe name that is globally available for use in any template across Angular apps. Pipe class implements the “PipeTransform” interfaces transform method that accepts an input value and returns the transformed result.

There will be one additional argument to the transform method for each parameter passed to the pipe. The pipe name is used for template bindings. To use the pipe you must set a reference to this pipe class in the module.

@Pipe({
  name: string
  pure?: boolean
})




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.