Angular 8 Interview Questions and Answers for 2024

Angular is one of the most popular and in demand open-source Web application development framework used by leading software and product-based companies around the world due to its features like fast and easy development, scalability, reliability and advance features, Angular is developed and maintained by Google and written in Typescript which a superset of JavaScript. A practical knowledge of Angular framework will open the doors to massive opportunities in the Software Industry for a Software Developer. Whether you are a beginner, intermediate or experience professional, this Angular 8 Interview questions blog will help you to clear various basic, intermediate and advanced concepts of angular like components, modules, component communication, services, pipes, directories, routes, content projection etc. This blog will help you to prepare for and ace your next interview to advance your career in Angular which happens to be one of the most in demand skills in market.

  • 4.7 Rating
  • 65 Question(s)
  • 30 Mins of Read
  • 8288 Reader(s)

Beginner

Angular is an open-source Web Development Framework written in Typescript. Angular is developed and maintained by Google. It is used for the development of Single Page Applications. Angular also has a large number of libraries that are open source and can be used within the Angular framework for building complex applications.

Angular uses TypeScript, which is a superscript of JavaScript. Typescript enables us to write JavaScript as a strong type of language that helps to identify and debug errors easily.

Angular is a modern web development framework that has various advantages over its predecessors 

Client-side rendering 

Angular Applications are rendered on the user's browser unlike other traditional web development frameworks where every page was requested from the server and then it was loaded into the browser. Due Client side rendering Angular applications are much faster than traditional web development frameworks. 

Single Page Application 

Applications developed using Angular are Single Page Applications i.e. the whole app does not requires to be loaded into the browser, only the page or module the user is currently interacting with is required to be loaded into the browser that makes Angular Applications faster and Lightweight. 

Excellent material Design Library 

Angular comes with Angular Material Design Library that allows designing of the UI/UX of the Application much faster and makes it more attractive and intractable. Angular material also has various templates available on Angular community forums that can be readily used to kick start the Angular Projects with design templates. 

Strong and Growing Community 

Angular has a strong community of developers that can be leveraged in case if developer is stuck and need help for any of the issues/challenges they face during development/maintenance of the application. Also, there are numerous tutorials that are easily available on the internet to learn Angular. 

Scalable and maintainable Architecture 

Unlike Traditional Web Development Frameworks, Angular Application is divided into various components, modules, services, routes that are easy to maintain and scale up as and when required. 

Angular is used for building a wide variety of Web/Mobile Applications, few of the use cases of Angular are: 

Building Large Enterprise Applications 

Angular 8 can be efficient for building large and complex Web Applications that cater the needs of a specific industry and run their businesses through these applications like CMS and LMS apps, Travel and Holiday Booking Apps, Social Media Sites, Content Publication Portals, E-Commerce Apps etc. 

Progressive Web Applications (PWA) 

Angular can be used to Build PWA, A progressive web app (PWA) is a website that looks and behaves as if it is a mobile app. PWAs are built to take advantage of native mobile device features, without requiring the end user to visit an app store, make a purchase and download software locally. Instead, a PWA can be accessed immediately through a browser. PWAs eliminate the need for e-commerce merchants to develop native apps for multiple mobile operating systems. 

Migrating old legacy Application to Modern Framework 

Applications built on technologies that are outdated need to be upgraded and migrated to a newer framework to fit the need of modern users and to leverage the advantage of modern technologies. Angular could be a perfect framework that can be used to migrate those old legacy platforms to a modern platform since Web API/Web services of those legacy applications can be entirely reused and just the front end needs to be built in Angular that will have better UI/UX and maintainability than the older application thus migrating legacy application to Angular saves a lot of time, cost and will provide better front end to the end users of the application. 

A must-know for anyone heading into an Angular interview, this question is frequently asked in Angular 8 interview questions.

Document Object Model 

The Document Object Model (DOM) is a programming interface for HTML and XML documents, DOM is rendered in the browser to display the UI. It represents a tree-like hierarchy for the structure of a document, with each node in the tree representing a part of the document (like an element, attribute, or text content). 

The DOM enables developers to programmatically access and manipulate the style, content, and structure of a document, and is often used in web development to make dynamic updates to a webpage. 

TypeScript 

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a superset of JavaScript and provides strict syntactical capabilities and adds optional static typing and other various features to the language. 

TypeScript's type system allows better code refactoring and editor support, which can help developers catch errors before they reach runtime, this makes it an appealing choice for large-scale applications. It also includes a number of features from the latest versions of JavaScript, such as async/await, de-structuring, and spread operators. 

Once code is written then it can be compiled into pure JavaScript that can be run in any browser or JavaScript runtime environment. It is widely used in Angular web frameworks and other JavaScript frameworks. 

Data Binding 

Data binding is a feature in Angular that allows you to create a connection between the component's template and the component's class (i.e .ts/.js file and .html file). Data Binding allows you to synchronize the data between the template and the class so that changes made in the template are reflected in the class, and vice versa. For the bidirectional data flow, Angular provides two-way data binding which can be achieved by using the Ng Model directive along with property and event binding. 

Testing 

Angular provides a powerful and comprehensive testing infrastructure that allows you to test different parts of your application even before making your application live or completely runnable. You can test components, services, pipes, and directives. The Angular CLI can generate a boilerplate code for you to test your component with a command. Additionally, Angular also has its own testing framework called Jasmine, along with the Karma test runner that runs the test in the browser and Protractor for E2E testing. 

In Angular, data binding is a way to synchronize the data between the component class and the template. When data in the model class changes, the template updates to reflect those changes and any change of data in the UI DOM will reflect in the model class. Data Binding is one of the core concepts of Angular and every application requires data binding to display the data from the backend on the front end and to capture the data from the front end to send it back to the backend. Some of the examples where data Binding is used are in interactive forms, calculators, games to show the points leader boards, to display the data in tabular format etc.

In Angular, data binding is the automatic synchronization of data between the component class and the view. There are four forms of data binding in Angular: 

  • Interpolation: Interpolation is a one-way data binding method that displays a component property in the template. 
  • Property binding: Property binding method that sets a component property to a value set in the template. 
  • Event binding: Event Binding is a one-way data binding method that responds to an event raised in the template, such as a button click. 
  • Two-way data binding: Two-way data binding synchronizes data between the component and the template in both directions. 

Here is an example of interpolation in Angular: 

<p>{{student.name}}</p>  

This will display the value of the name property of the student object in the template. 

Here is an example of property binding in Angular: 

<input [value]="student.name"> 

This will set the value of the input field to the value of the name property of the student object. 

Here is an example of event binding in Angular: 

<button (click)="onSave()">Save</button> 

This will call the onSave() method in the component class when the button is clicked. 

Here is an example of two-way data binding in Angular: 

<input [(ngModel)]="student.name"> 

This will synchronize the value of the name property of the student object with the value of the input field in both directions. Any changes to the input field will be reflected in the component class, and any changes to the name property in the component class will be reflected in the input field.

In Angular, a template is a form of HTML that tells Angular how to render the component. A template is a declarative way to define a component's view. It can include HTML, CSS styles, and Angular directives.  

The template is used to define the component's user interface, and it is used in conjunction with the component's class, which handles the component's logic. 

Here's example of Angular Template: 

<h1>{{title}}</h1> 
<ul> 
<li *ngFor= "let student of students"> 
{{ student.name }} 
</li> 
</ul> 

This template displays a heading with the value of the title property, and it also displays a list of students using the ngFor directive. The ngFor directive is used to iterate over an array of students and generate a list item for each student.  

The template is combined with the component class to make a view displayed to the user. The component class is responsible for handling the component's logic, while the template is responsible for defining the component's user interface.  

You can define a template in Angular in several ways, including directly in the component file, in a separate HTML file, or in a script tag in the component file. The template can also include references to other components or directives, allowing you to create complex and reusable user interfaces.

JIT stands for "Just-In-Time" compilation. In Angular, JIT refers to the process of compiling Angular components and templates at runtime, when the application is loaded in the browser. 

One of the main advantages of JIT compilation is that it allows for faster development and debugging, as the compilation happens in the browser, you can see the changes immediately after just refreshing the browser, so you don't need to rebuild the application and reload the browser. 

The main disadvantage of JIT compilation is that it can cause performance issues as the application grows larger, as the compilation process takes place at runtime, it can slow down the initial loading time of the application. 

Command for JIT Compilation is: 

ng build 
ng serves 

AOT stands for "Ahead-of-Time" compilation. In Angular, AOT means the process of compiling Angular components and templates ahead of runtime, i.e., during the build process. 

The Angular compiler converts the component's templates and component's classes into JavaScript code that can run directly in the browser, without further processing. This makes application load faster, as the browser doesn't need to process and compile the templates at runtime. 

When using AOT compilation, the Angular compiler will check the templates for errors during the build process itself, this helps in catching the potential issues before the application is deployed. It also generates smaller, more efficient code that can run faster and take up less memory. 

The main advantage of AOT compilation that it improves performance in production environments, since the compilation process happens during the build time, the application will have faster load time and improved runtime performance. The main disadvantage is that it increases the build time and it doesn't allow you to see the changes in real time as in JIT compilation. 

Command to run AOT compilation is: 

ng build --aot 
ng serve --aot 

There are several advantages of using Ahead-of-Time (AOT) compilation in an Angular application: 

  • Improved Performance: AOT compilation generates highly optimized code that run faster and take up less memory in the browser, this results in improved overall performance and faster load times for the application. 
  • Better Security: AOT compilation catches potential security issues during the build process, such as XSS (Cross-site scripting) attacks, by eliminating the need for the browser to evaluate untrusted templates at runtime. 
  • Better Developer Experience: AOT compilation catches the template errors during the build process, which helps the developers identify and fix issues earlier in the development cycle. 
  • Smaller Bundle Sizes: As AOT precompiles the templates, the resulting JavaScript code is typically smaller than the equivalent JIT-compiled code, this results in faster load times and reduced data transfer costs. 
  • Better SEO: AOT compilation allows you to generate static HTML files that can be served to the browser, which makes it easier for search engines to index your application and improve its search engine visibility. 
  • Reduced Load on the Client: With AOT, most of the processing happens on the build machine, which reduces the load on the client browser and allows for smooth rendering of applications in client's browser. 

Note that AOT is best suited for production environments where performance and security are critical concerns, it is not a requirement for development environment, but it can be used for catching errors early on.

Angular 8 interpolation is a feature that allows us to insert dynamic values into the template. It is a one-way data binding technique that allows us to display the value of a component's property in the template. 

Interpolation uses double curly braces ({{ }}), and the value (variable that has the value) inside the braces is the property or expression that is evaluated and the result is displayed in the template. 

For example, if we have a component with a property called "name" and we want to display the value of that property in the template, we can use interpolation like this: 

<h3> 
{{name}} 
</h3> 

Here, the value of the "name" property will be displayed inside the <h3> element, the text value within the {{ }} is evaluated as a property or expression. 

Interpolation is a one-way data binding; it can only update the view when the data is changed in the component class and does not reflect the changes in the template back to the component class. 

Expect to come across this popular question in Angular 8 interview questions and answers for freshers. Angular creates and renders components along with their children, checks when their data-bound properties change, and destroys them before removing them from the DOM. 

Angular offers lifecycle hooks that provide visibility into these key life moments and the ability to act when they occur. 

  • ngOnChanges(): This hook is called when an input binding value changes, it is used for Angular change detection. 
  • ngOnInit(): This hook is called after the first ngOnChanges() and is often used for initializing the component. 
  • ngDoCheck(): This hook is called during every change detection run and is used for custom change detection. 
  • ngAfterContentInit(): This hook is called after a component's content has been initialized and is used for interacting with the projected content. 
  • ngAfterContentChecked(): This hook is called after a component's content has been checked and is used for interacting with the projected content. 
  • ngAfterViewInit(): This hook is called after a component's view has been initialized and is used for interacting with the view. 
  • ngAfterViewChecked(): This hook is called after a component's view has been checked and is used for interacting with the view. 
  • ngOnDestroy(): This hook is called just before a component is destroyed and is used for cleanup, such as unsubscribing from observables. 

In Angular, both the constructor and the ngOnInit hook are used to initialize a component, but they both serve different purposes and have different use cases. 

The constructor is a standard JavaScript method called when an object is created. In Angular, the constructor is used for dependency injection and for initializing the component with a set of inputs that can be used throughout the component. The constructor is called before the component's data-bound properties are initialized, so it cannot be used to access or modify the component's template or state. 

On the other hand, ngOnInit is an Angular lifecycle hook that is called after the component's data-bound properties have been initialized. It is invoked by Angular's change detection mechanism after the first round of change detection is completed, this makes sure that the component and its children are fully utialized, and the inputs are set. We can access the component's template and state and perform any additional initialization logic using this hook. 

export class App implements OnInit{ 
constructor(){ 
//called first time before the ngOnInit() 
} 
ngOnInit(){ 
//called after the constructor and called after the first ngOnChanges() 
} 
} 

Angular app can be created using Ng commands as below 

ng new <appname> 

For eg: ng new myfirstapp 

Once the command ran successfully it will create a boilerplate along with files package.json that will have all the app dependencies, default module and component files like app.module.ts, app.component.ts, assets and environment files and other necessary meta data files for us. We can use this boilerplate to further design and develop our Angular app as per our requirements. 

In Angular, a component is one of the main building blocks of the application that controls a portion of the screen, called a view. It is a combination of a template (HTML), logic (JavaScript or TypeScript), and styles (CSS) that define a specific behavior/functionality and look and feel of a part of the UI. 

A component defines a class with properties and methods, and it also includes a template (HTML file) that defines the component's view, as well as metadata that tells Angular how to use the component. 

A component typically corresponds to a certain element on the screen, like a button, a form, or a card. Each component can have its own behavior, logic and data. 

Components are the basic building blocks of an Angular application, and they can also be nested inside other components to create a hierarchical structure for the UI. This allows for reusability, modularity and easily maintainable code. 

Each component has a lifecycle managed by Angular which allows us to tap into certain points during the lifecycle through lifecycle hooks and perform specific actions, such as setting up the component's initial state or cleaning up after it is destroyed. 

In Angular, components are created using the @Component decorator, which allows us to configure the component's metadata. Some of the metadata options include the component's selector, template, styles, and inputs/outputs 

import { Component } from '@Angular/core'; 
@Component ({ 
selector: 'my-app', 
template: ` <div> 
<h1>{{title}}</h1> 
<div>Learn Angular8 with examples</div> 
</div> `, 
}) 
export class AppComponent { 
title: string = 'Hello from Angular !'; 
} 

In Angular 8, a service is a class that encapsulates some common business logic or functionality that must be reused throughout the application. A service is typically used for: 

  • Sharing data or state across multiple components 
  • Encapsulating and abstracting complex logic or external interactions (such as fetching data from a server) 
  • Managing application-wide state 
  • Implementing cross-component logic 

Services in Angular are typically used for separation of concerns of our application. They provide a way to share data and logic across multiple components, without creating tight coupling between them like objects of the class. This allows us to change the implementation of a service without affecting the components that use it. 

Angular services are singleton objects, this means that there is only one instance of the service and it is instantiated only once during the lifetime of an application. Once a service is created, it can be injected into any component or other service that needs it. 

Services are created using the @Injectable decorator and are usually registered with a provider in the @NgModule decorator of the module that uses the service. This makes the service available for injection into other parts of the application. 

import { Injectable } from '@Angular/core'; 
import { Http } from '@Angular/http'; 
@Injectable() 
export class RepositoryService{ 
constructor(private http: Http){ 
} 
fetchAll(){ 
return this.http.get('https://api.github.com/repositories') 
.map(res => res.json()); 
} 
} 

Dependency injection in Angular 8 is a technique for creating and managing instances of objects that a component depends on. These objects, known as dependencies, are typically services or other types of classes. Rather than creating these dependencies directly within the component, they are instead provided to the component through a process called injection. This allows the component to remain independent of the specific implementation of its dependencies and makes it easier to test and manage the component. 

In Angular 8, Dependency injection is achieved through a powerful and flexible inversion of control (IoC) container, that is implemented in the @Angular/core package. This IoC container automatically creates and manages the instances of the dependencies for the component, and wires them up to the component using the appropriate injection mechanism. 

To use dependency injection in an Angular 8 application, we need to provide the dependencies that a component or service depends on, by registering them with the Angular's injection system using the @Injectable decorator. Then in the constructor of the component or service, we can ask for the dependencies by typing them as parameters, then Angular's DI system will automatically inject the registered dependencies into the component/service constructors. 

Another Angular 8 feature interview question commonly asked is about the types of directives. Directives are the class that adds additional behavior to elements in our Angular Applications 

There are mainly three kinds of directives. 

  • Components Directives: Component directives are the most used directives in Angular 8, It contains HTML templates to bind on our web Page, a selector that is used to bind the entire component to HTML DOM and styles to apply style and CSS to our component DOM. Component Directives start with @Component Decorator. 
  • Structural directives: These directives change the DOM layout by adding and removing DOM elements. The Structural elements can directly be used into template by appending * before the directive for eg: *ngFor, *ngIf etc. 
  • Attribute directives: These directives is used to change the appearance or behavior of an element, component, or another directive by modifying the attributes of DOM elements. 

Decorators are a fundamental concept in TypeScript, it acts as metadata for Angular Application, and because Angular heavily relies on TypeScript, decorators have become an important element oAngular as well. Decorators are methods or design patterns that are prefixed with @ symbol and preceded by a class, method, or property. A decorator provides configuration metadata that specifies how a component, class, or method should be processed, constructed, and used at runtime. Angular includes several decorators which attach various types of metadata to classes, allowing the system to understand what all these classes signify and how they should function. 

Types of decorators: 

  • Class decorators: Class decorators are applied to a class, such as @Component and @Injectable. They provide additional information or functionality to the class and its members. 
  • Property decorators: Property decorators are used as class property, such as @Input() and @Output(). They provide additional information or functionality to the class properties and are used to configure data binding and events. 
  • Method decorators: Method decorators are applied to a class method, such as @HostListener. They provide additional information or functionality to the class methods; they can be used to attach a method to an event in the host element. 
  • Parameter decorators: Parameter decorators are used in parameters of a class constructor or method, such as @Inject(). They provide additional information or functionality to the constructor or method and are used for dependency injection. 

Angular Material is a UI component library for Angular, that provides a diverse range of pre-built, reusable, and accessible UI components and tools for building responsive, attractive and elegant user interfaces. 

Material Design provides a consistent visual language, as well comes with guidelines for layout, typography, and more. By using Angular Material, developers can easily implement Material Design create visually appealing and consistent user interfaces for Angular Applications. 

Angular Material provides a variety of UI components such as: 

  • Form controls like input, select, checkbox, date picker etc. 
  • Navigation like side nav, toolbar, menu, etc. 
  • Layout like grid list, card, tab, etc. 
  • Buttons, Indicators, and icons, Popups and modals 

It also offers some services for theming, accessibility and internationalization. 

Run following command to install Angular Material to our project: 

npm install @Angular/material @Angular/cdk

In Angular, pipes are a way to transform data, by applying a set of pre-defined or custom logic to a value, before displaying it in the template/UI. Pipes are used to format data for display and perform simple data transformations. 

Pipes are denoted by the "|" (pipe) symbol in a template, followed by the pipe's name. 

With Pipes we can easily format and transform data in our templates, without writing additional logic in our components 

@Pipe decorator is used for Pipe. 

Syntax for pipe is as follows 

{{ data | pipename  }} where data is the data to display in DOM, | separator is the symbol for pipe, pipename is the name of our pipe.

In Angular 8, we can choose to define our component's template either in one of the two ways i.e., inline, as part of the component's class definition, or in an external file. 

Both options have their advantages and use cases that it is suited for, and we can choose the one that best fits our needs. 

Using an inline template is useful when: 

  • The template is relatively small and simple, as it can make the component class definition more concise and easier to read. 
  • We don't want to reuse the template for multiple components. 
  • We want to take advantage of the syntax highlighting, auto-completion and error checking features of our code editor 

Using an external template is useful when: 

  • The template is large or complex, as it can make the component class definition more readable and maintainable by moving the DOM code to template file. 
  • We want to reuse the template for multiple components. 
  • We want to keep the component class definition and the template in separate files, to improve the organization and maintainability of our application.

The ngIf directive in Angular is a structural directive that is used to conditionally add or remove an element and its children from the DOM based on a given expression. It evaluates the expression and if it's truthy, the element and its children are added to the DOM, otherwise it's removed. 

We can conditionally control the visibility of an element, by adding or removing it from the DOM. This can be useful in several cases, such as: 

  • Showing or hiding a certain element based on some condition, such as a user's permissions, flag or the state of the application. 
  • Dynamically loading or unloading content based on user interactions in the application or other events. 

Example of ngIf directive to display the paragraph only if user is more than 18 years of age 

<p *ngIf=" user.age > 18">You are not eligible for student pass!</p>

The ngFor directive in Angular is a structural directive that is used to iterate over a collection of data and generate a template for each item in the collection. It is used to repeat a part of the template for each item in an array or an object that implements the iterable interface. 

It can also be used to generate dynamic content in the template, by repeating the same structure for each item in a collection. This can be useful in several cases, such as: 

  • Generating a list of items from an array or array of object 
  • Creating reusable templates 
  • Creating dynamic tables and forms 

For example, here we iterate over list of users where users in an array of users 

<li *ngFor= "let user of users"> 
{{ user }} 
</li> 

We can import third-party libraries by installing them through npm and then importing them into our app.module.ts file. 

Here are the steps to import a third-party library in an Angular 8 application: 

  1. Install the library using npm by running the command npm install <library-name> in the root of our project. 
  2. In the app.module.ts file, import the library by adding the following line of code at the top of the file: import <library-name> from '<library-name>' 
  3. Add the library to the @NgModule decorator's imports array.

Intermediate

Every application has at least one Angular module, the root module that we bootstrap to launch the application is called a bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows, 

import { BrowserModule } from '@Angular/platform-browser'; 
import { NgModule } from '@Angular/core'; 
import { FormsModule } from '@Angular/forms'; 
import { HttpClientModule } from '@Angular/common/http'; 
import { AppComponent } from './app.component'; 
/* the AppModule class with the @NgModule decorator */ 
@NgModule({ 
declarations: [ 
AppComponent 
], 
imports: [ 
BrowserModule, 
FormsModule, 
HttpClientModule 
], 
providers: [], 
bootstrap: [AppComponent] 
}) 
export class AppModule { } 

One of the most frequently posed Angular 8 Interview Questions, be ready for it. Passing the data between the components is Component data communication. Component data communication is mainly of two types i.e Parent to Child and Child to Parent 

Parent to Child: 

Parent to child data sharing passes data from the parent component to the child component with the help of @Input Decorator() 

Child to Parent: 

Passing data from child to parent component is Child to Parent data communication which is done using @Output() decorator 

Here's the example of Parent to Child communication. 

landing-page-component.ts 

import { Component, OnInit } from '@Angular/core'; 
@Component({ 
selector: 'app-landing-page', 
templateUrl: './landing-page.component.html', 
styleUrls: ['./landing-page.component.css'] 
}) 
export class LandingPageComponent implements OnInit { 
constructor() { } 
studentMarks = [{subject: "Maths", score: 75}, {subject: "Science", score: 80}, {subject: "History", score: 50}]; 
myResult: any 
ngOnInit(): void { 
} 
displayResult($event: any) { 
this.myResult = $event; 
} 
} 

landing-page-component.ts 

<div> 
<app-result-page [marks]="studentMarks" (emitresult)="displayResult($event)"></app-result-page> 
<b>{{myResult}}</b> 
</div> 

result-page-component.ts 

import { Component, Input, OnInit, Output, EventEmitter } from '@Angular/core'; 
@Component({ 
selector: 'app-result-page', 
templateUrl: './result-page.component.html', 
styleUrls: ['./result-page.component.css'] 
}) 
export class ResultPageComponent implements OnInit { 
@Input() marks: any; 
@Output() emitresult = new EventEmitter() 
result: any; 
constructor() { } 
ngOnInit(): void { 
console.log('YOUR MARKS ARE:'this.marks); 
if (this.marks.filter((x: any) => x.score < 50).length > 0) { 
this.result = 'You Failed'; 
else { 
this.result = 'You Passed'; 
} 
this.emitresult.emit(this.result); 
} 
} 

result-page-component.html 

<div> 
<div *ngFor= "let mark of marks"> 
{{mark.subject}} {{mark.score}} 
</div> 
</div> 

Output: 

We created two components namely LandingPage which is our Parent component and ResultPage which is Child component. 

Firstly, we passed student marks from Landingpage to ResultPage i.e Parent to Child component using 

[marks]="studentMarks" 

In landing-page-component.html and accessing the value of studentMarks in result-page-component.ts via @Input() decorator 

In result-page-component.ts we need to return the result whether the student is padded or failed to the parent component by checking if any score is less than 50 the student is failed else they are passed. 

Once we get this result, we pass this on to the parent component i.e landing-page-component.ts via the @Output decorator and access the result in Parent component via function displayResult() in landing-page-component.ts which is triggered by landing-page-component.html by below event and store it in myResult variable 

(emitresult)="displayResult($event)" 

and finally, we display the result via interpolation 

<b>{{myResult}}</b> 

ngOnChanges() is a lifecycle hook in Angular that is called whenever a data-bound property value changes, it is used for change detection. The hook method is passed a SimpleChanges object that contains the current and previous property values. It is commonly used to update a component's internal state or perform some other action in response to a change in an input property. The ngOnChanges() method is called whenever a bound input property changes. 

It uses SimpleChanges Object to get the latest changes in @Input(), we can see the previousValue and currentValue with the help of SimpleChanges object 

Here's the example of ngOnChanges() lifecycle hook: 

We have created a input control in InputComponent and stored the value of input control in a variable name. We pass this name as an @Input() to the child component i.e DisplayComponent, inside DisplayComponent we use ngOnChanges() LifeCycle hook to get the current and previous changes 

input.component.ts 
import { Component, OnInit, OnChanges } from '@Angular/core'; 
@Component({ 
selector: 'app-input', 
templateUrl: './input.component.html', 
styleUrls: ['./input.component.css'] 
}) 
export class InputComponent implements OnInit { 
constructor() { } 
name: string = ""; 
ngOnInit(): void { 
} 
updateName(text: any ) { 
// console.log('updated name:',text.target.value); 
this.name = text.target.value; 
} 
} 

input.component.html 

<div> 
<p>Enter you name:</p> 
<input type="text" (keyup)="updateName($event)"> 
<app-display [myName]="name"></app-display> 
</div> 

display.component.ts 

import { Component, Input, OnInit, OnChanges, SimpleChanges, SimpleChange } from '@Angular/core'; 
@Component({ 
selector: 'app-display', 
templateUrl: './display.component.html', 
styleUrls: ['./display.component.css'] 
}) 
export class DisplayComponent implements OnInit { 
@Input() myName : any 
constructor() { } 
ngOnInit(): void { 
console.log('Input is:'this.myName); 
} 
ngOnChanges(changes: SimpleChanges) { 
console.log(JSON.stringify(changes['myName'])); 
} 
} 

ngOnChanges()

ngOnChanges()

A promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. 

Promises in Angular provide a way to handle asynchronous data and simplify the process of working with asynchronous code. A promise has one of three states: pending, fulfilled, or rejected. When a promise is pending, it means that the asynchronous operation has not yet completed. 

When the operation completes successfully, the promise becomes fulfilled and its resulting value is made available. If the operation fails, the promise becomes rejected. 

A promise can be "subscribed" to using the then() method, which takes two callback functions: one for handling the fulfilled case, and one for handling the rejected case. 

In Angular, promises are commonly used to handle HTTP requests, as well as other asynchronous operations, such as timers and animations 

  • fulfilled - The action relating to the promise succeeded 
  • rejected - The action relating to the promise failed 
  • pending - Hasn't fulfilled or rejected yet 

Promises can be executed by calling the then() and catch() methods. 

The then() method takes two callback functions as parameters and is invoked when a promise is either resolved or rejected. 

The catch() method takes one callback function and is invoked when an error occurs. 

Here's an example of a promisecatch() method

async and await are keywords in JavaScript that allow developers to write asynchronous code that executes synchronously 

async is a keyword that is used before a function declaration to indicate that the function contains asynchronous code. It tells the JavaScript interpreter that the function should return a promise. 

await is a keyword that is used inside an async function to pause the execution of the function until a promise is fulfilled. When the await keyword is used with a promise, the JavaScript interpreter waits for the promise to resolve and then assigns the resolved value to the variable on the left of the await keyword. 

Here's an example of async await keywords: 

We create a funcA that returns a promise after 2 seconds and functB that is marked as async, inside funcB we await the function a to return the promise result, once result is returned, we console the result of funcA. 

function funcA() { 
return new Promise((resolve,reject) => { 
setTimeout(() => { 
resolve('Promise resolved') 
}, 2000); 
}) 
} 
async function funcB() { 
var result = await funcA(); 
console.log(result); 
} 
funcB() 

Modules is basically grouping of multiple components, services, directives together to from a standalone unit of Application. 

For example, let us assume that we are building an E-Commerce web application, this application will have various key functionality like Login/register, Product listing, Shopping cart, Payment Gateway etc. Each of these functionalities will be developed using multiple components, pipes, directives etc. for it to work, this collection of Components, pipes, directives is grouped together in a Modules such that all that is required for a particular functionality to work is inside a Module that covers that functionality. This improves Application performance, makes it lightweight and maintainable the code. 

To define module, we can use the NgModule. When we create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows 

import { BrowserModule } from '@Angular/platform-browser';import { NgModule } from '@Angular/core';import { AppComponent } from './app.component'; 
@NgModule({ 
   declarations: [ 
      AppComponent 
   ], 
   imports: [ 
      BrowserModule 
   ], 
   providers: [], 
   bootstrap: [AppComponent]}) 
export class AppModule { } 

The Router is a module that is used for navigating between different views (components) in an application based on user interaction with the application. The router enables us to navigate between different parts of our application without the need for a page reload, which improves the user experience. 

The Angular Router enables developers to map specific URL patterns to a component, so that when a user navigates to that URL, the router will automatically instantiate and display the appropriate component. The router also allows for passing parameters to components through the URL, and it can also maintain the application's state and handle navigation events. 

To use the Angular Router, we need to import the RouterModule and Routes from the @Angular/router package. 

RouterModule is the main module for the router and the Routes is an array of route configuration objects. 

The Angular Router also provide a different way to navigate, we can navigate by URL, navigate with route's name, navigate with relative path and pass parameters, navigate with query parameters and many more. 

Here are some common use cases for using services in Angular: 

  • HTTP communication: Services are commonly used to handle HTTP requests to a server, such as sending data or retrieving data. By placing http logic in a service, it can be reused across multiple components that eliminates the need for duplicating the same logic in multiple places. 
  • Shared state: Services can be used to share state across multiple components. For example, if multiple components need to know a certain value, this state can be stored in a service and then injected into the various components that need it. 
  • Utility functions: Services can contain utility/common functions that can be reused across multiple components, such as validation logic, formatting logic, or any other type of logic that is needed by multiple components. 
  • Centralized data management: Services can be used to centralize the management of data, such as fetching data from a server or managing the data in memory. This keeps the data management logic in a single place and makes it easier to maintain the application. 
  • Intercomponent communication: Services can be used to facilitate communication between components that are not in a parent-child relationship. For example, one component may want to notify another component when an event occurs, this can be done using services. 
  • Dependency injection: Services can be easily injected into components by Angular's dependency injection system, making it easy to use the service across multiple components and making the codebase more maintainable and compact. 

Angular Observables is used for transmitting or passing the data from one component to another or from a service to a componentObservables is one of the core concepts of Angular which is used for Asynchronous Programming. 

Observables do not execute on its own, it only executes and passes the data when someone subscribes to it. The method that emits the value when subscribed is called Observable and the method that subscribes to the Observable is called subscriber. 

One of the common use cases of observables in Angular is calling an API end point asynchronously and returning the result back to the subscriber once the API execution is complete and it returns the response. 

See the example below where we call an http endpoint and mark the function as Observable and then subscribe the Observable function to get the asynchronous response 

getApiRespnse(): Observable<any> { 
return this.http.get(apiUrl); 
); 
} 
this.apiService.getApiResponse().subscribe((res) => { 
console.log('APi response from observable is:', res); 
}) 

Both Promises and observables are a way to handle asynchronous data in JavaScript, but they have some key differences. 

Promises: 

  • A promise represents a single value that will be returned at some point in the future. 
  • Once a promise is fulfilled or rejected, it cannot change state. 
  • A promise can be used only once. 
  • A promise can be consumed by using the then method, which allows to attach callbacks for when the promise is fulfilled or rejected. 

Observables: 

  • An observable is a stream of values that can emit multiple values over time. 
  • Observables are lazy, the source only starts to emit values when you subscribe to it. 
  • An observable can emit multiple values over a period of time, unlike a promise which only resolves a single value. 
  • An observable can be consumed by subscribing to it, this allows to attach multiple callbacks to the stream of values and allows to handle errors and complete events. 
  • Observables allow to use operators to transform and filter the stream of data. 

In general, we can use promises for one-time-events and when the use-case is simple and we don't expect multiple values. On the other hand, observables are more powerful and should be used when working with async data streams, multiple values and complex use-cases where we need operators for the data flow. 

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables, to make it easier for composing asynchronous and event-based programs. 

An observable is a stream of values that can emit multiple values over time, similar to an event. With RxJS, we can create observables from a wide variety of data sources such as events, promises, or even plain arrays, and we can use them to transform, filter, and compose streams of data. 

RxJS provides a large set of operators that we can use to transform and filter the data in an observable stream. These operators include basic operations such as mapfilter, and reduce, as well as more advanced operators like mergeconcatswitchMap, and debounceTime. 

RxJS also allows us to handle errors in the observable stream, with error handling operators like catchError, and it provide a way to complete the stream with complete and finally operators. 

RxJS is widely used in Angular for handling asynchronous data and events. Angular's HTTP client and the Angular Router both use RxJS observables, and many third-party libraries also rely on RxJS. The library is also commonly used in other types of web and mobile development to handle asynchronous events, real-time communication and data streams. 

RxJS is a powerful library, but it requires a certain level of understanding to effectively use it. Understanding the concepts of observables, operators, and the observer pattern will help us to use RxJS effectively. 

  • Components: These are the basic building blocks of an Angular application. Each component controls a portion of the screen, called a view, and manages a small section of the overall application logic. 
  • Templates: These define the layout of a component's view and determine how the component's data is displayed. Templates are written using HTML, CSS, and Angular's template syntax. 
  • Services: These are used to share data and functionality across different parts of the application. Services are typically used to encapsulate business logic or to interact with a server. 
  • Modules: These are used to organize an Angular application by grouping together related components, services, and other pieces of functionality. 
  • Data binding: This is the mechanism that Angular uses to connect a component's view with its underlying data model. Data binding makes it easy to update the view when the data model changes and vice versa. 
  • Dependency injection: This is a mechanism that Angular uses to manage the dependencies of different parts of an application. Dependency injection makes it easy to replace or mock dependencies in different parts of the application. 
  • Routing: This is the mechanism that Angular uses to navigate between different views in an application. Routing allows us to define different URLs for different parts of the application and to easily navigate between them. 

Angular provides several built-in pipes that we can use in our templates to transform data. Here is a list of some commonly used built-in pipes in Angular: 

  • date: Formats a date according to the specified format. 
  • currency: Formats a number as currency. 
  • decimal: Formats a number as a decimal. 
  • percent: Formats a number as a percentage. 
  • json: Converts a value to JSON string. 
  • lowercase: Transforms a string to lowercase. 
  • uppercase: Transforms a string to uppercase. 
  • async: Waits for a promise or an observable to emit a value and then transforms it. 
  • slice: Extracts a section of an array or a string. 
  • i18nSelect: Transforms a value into a string based on the current locale. 
  • i18nPlural: Chooses a value from an object based on the plural category of the value. 
  • KeyValue: Transforms an Object to an array of key value pairs. 
  • titlecase: Transforms a string to Title Case 
  • number: Formats a number to a string. 
  • percent: Formats a number as a percentage. 

In Angular 8, the HttpClient module is a built-in module that allows us to make HTTP requests. It is part of the @Angular/common/http package and can be imported in our component or service to make use of its methods. The HttpClient module replaces the previous Http module and has some added features such as support for typed return values and interceptors. With HttpClient, we can make requests using methods such as GET, POST, PUT, DELETE, etc. and handle the response with observables.  

Angular common modules are a collection of modules that provide utility functions and services that are commonly used by other parts of an Angular application. These modules are part of the @Angular/common package, which is a built-in package included with an Angular application. 

Some of the common modules that are part of this package include: 

  • FormsModule: provides directives and services for building forms in Angular. 
  • HttpClientModule: provides an HttpClient for making HTTP requests 
  • CommonModule: provides a set of common directives and pipes that are often used by other modules in an application, such as ngIf and ngFor. 
  • PlatformLocation : Gives information about the current location of the application 
  • BrowserModule : Provides services and directives that are specific to web browsers. 
  • LocationStrategy : abstract class used to configure the service that is used to look up the location of a component in the DOM 

These modules are automatically imported in @NgModule when we create a new Angular application using Angular CLI. 

ng-container is a syntax element that is used to render the data in the HTML without actually taking up the space in the DOM. ng-container as an element does not render in DOM unlike span, div tags, only the data inside the ng-container element is rendered. 

This is quite useful when we want to render the data based on certain conditional statement but don't want to take up unnecessary DOM space for the conditions that are not satisfied. 

See example below: 

<ng-container *ngIf="marks >= 50"> 
<p>Your have Passed the Exam</p> 
</ng-container> 
<ng-container *ngIf="marks < 50"> 
<p>Your have Failed the Exam</p> 
</ng-container> 

localStorage is used to store the data in the user's browser to access it at some later poinin time. Usually some frequently used data is used in the localStorage so that is can be accessed again without the need to fetch or calculate the result again. We can set the localStorage by giving it a unique name and also retrieve the data stored into localStorage by its name 

Example of Using storing data into localStorage: 

localStorage.setItem('discountedPrice', price); 

Example of reading stored value from localStorage: 

var priceAfterDiscount = localStorage.getItem('discountedPrice'); 

In Angular, routing allows us to navigate between different views or pages of our application. To route from one page to another, we need to set up routing in our application by configuring routes and a router outlet. 

Here's an example of how we might set up routing in an Angular application: 

First, we need to import the RouterModule and Routes from @Angular/router in our app.module.ts file. 

Next, we need to create an array of routes, where each route is an object with a path and a component property. The path property is the URL path that the route corresponds to, and the component property is the component that should be displayed when the route is activated. 

import { CommonModule } from '@Angular/common'; 
import { Routes, RouterModule } from '@Angular/router'; 
import { HomeComponent } from './home/home.component'; 
import { ContactUsComponent} from './about/contactUs.component'; 

Underneath the imports, add a new routes array to store the paths that we will use when routing to each page. 

const routes: Routes = [ 
  path''componentHomeComponent }, 
  path'contactUs'componentContactUsComponent} 
]; 

Replace the NgModule block with the following, which adds the RouterModule to the imports and exports array. 

@NgModule({ 
  declarations: [], 
  imports: [ 
    CommonModule, 
    RouterModule.forRoot(routes) 
  ], 
  exports: [RouterModule] 
}) 

In our HTML file where we wish to route from add 

<div class="navbar"> 
  <a class="link" href="">Home</a> 
  <a class="link" href="/contactUs">Contact Us</a> 
</div> 

In Angular, a routerLink is a directive that allows us to create links between different routes in our application. When we create a link using the routerLink directive, it automatically updates the displayed component when the link is clicked. 

We can use the routerLink directive in an a element or any other elements like button in our template to create a link to a specific route. The value of the routerLink directive is a string or an array of link parameters that correspond to the route we want to navigate to. 

<h1>Angular Router</h1> 
<nav> 
<a routerLink="/home" >Home</a> 
<a routerLink="/user" >Users</a> 
</nav> 
<router-outlet></router-outlet> 

An active routerLink is a state of the routerLink directive, it will add a CSS class to the link element when the current route matches the link route. 

We can use the routerLinkActive directive to add a CSS class to an element when the route becomes active. For example, we could use the routerLinkActive directive to highlight the currently active link in a navigation menu like this: 

<h1>Angular Router</h1> 
<nav> 
<a routerLink="/home" routerLinkActive="active">Home</a> 
<a routerLink="/user" routerLinkActive="active">Users</a> 
</nav> 
<router-outlet></router-outlet> 

Angular has large number of third party libraries that we can use in our application to enhance the performance and develop applications quickly with ready to use functions using these libraries. We need to install these libraries using npm install and use in our project as follows: 

Install the library: 

npm install --save underscore 

Use the Library in Angular component: 

import * as _ from 'underscore'; 
export class AppComponent { 
constructor() { 
const myArray: number[] = [915]; 
const lastItem: number = _.last(myArray); //Using underscore 
console.log(lastItem); //5 
}} 

Advanced

A staple in advanced Angular 8 interview questions, be prepared to answer this one. Pipes are used to transforming the way how information is visible to the user. Apart from built-in pipes Angular also gives us the provision to implement our own pipes, these customized pipes as per our need is called Custom pipes. Angular Pipes are TypeScript classes with the @Pipes decorator. 

Here is an example of a pipes that display Pass or Fail beside the students subject if marks is greater than equal to 50 else Fail 

result.pipe.ts 
import { Pipe, PipeTransform } from '@Angular/core'; 
@Pipe({ 
name: 'result' 
}) 
export class ResultPipe implements PipeTransform { 
transform(value: number): string { 
if (value >= 50) { 
return 'Pass' 
else { 
return 'Fail' 
} 
} 
} 

result-page.component.html 

<div> 
<div *ngFor= "let mark of marks"> 
{{mark.subject}} {{mark.score | result}} 
</div> 
</div> 

Output: 

In Angular, a pipe is a way to transform data before displaying it in a template. Some pipes, called "parameterized pipes," take an additional parameter as input in order to control their behavior. 

A parameterized pipe is defined by using the : character followed by the parameter value, for example {{value | myPipe:parameter}} 

Let us take an example where we need to pass parameter with a date pipe. 

<p>Full Date : {{today | date:'fullDate'}}</p> 

Here date is Angular pipe and 'fullDate' is the parameter that we pass to the date pipe 

In our pipe.ts file we can access the argument as: 

transform(value: number, param: string): string { 

Where param is the argument you passed to pipe 

Pipe chaining is a method of connecting the output of one pipe the input of another, in order to perform a series of operations on the data. This can be done by using the "pipe" symbol (|) in a command-line interface, which takes the output of the command before the symbol as the input of the command after the symbol. This allows multiple commands to be combined into a single, more powerful command Refer the example below: 

<h2>Your result is - {{ marks | result | uppercase}} </h2> 

 we used custom pipe "result" and chained it with anothepipe "uppercase", where result is a custom pipe and uppercase is inbuilt pipe. 

Pure pipe is a pipe that runs only when a pure change is detected, by pure change we mean change in primitive datatypes like boolean, string, number or object reference change. 

Impure pipes are pipes that runs when object is changed. Changes within objects, array will be detected by impure pipe. 

Pipes are pure by default, to make the pipe impure we need to add pure: false inside the @Pipe() decorator. 

import { Pipe, PipeTransform } from '@Angular/core'; 
@Pipe({ 
name: 'result', 
pure: false 
}) 
export class ResultPipe implements PipeTransform { 
transform(value: number, param: any): string { 
if (param.isPassed) { 
return 'Pass' 
else { 
return 'Fail' 
} 
} 
} 

Outgoing requests and incoming responses can be intercepted in Angular 8 using HTTP Interceptors. HTTP Interceptor sits between client and server; hence Interceptors have access to any http request made from client to the server and response from server to the client. Interceptors can also be used to modify the request object and response data. 

We can create an interceptor by creating interceptor.ts file and adding the required dependencies as seen below 

interceptor.ts 

import {Injectable} from "@Angular/core"; 
import {HttpEvent, HttpHandler, HttpInterceptor,HttpRequest} from "@Angular/common/http"; 
import {Observable} from "rxjs"; 
import { tap } from "rxjs/operators"; 
@Injectable() 
export class AppHttpInterceptor implements HttpInterceptor { 
constructor() { 
} 
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
console.log('request log:', req); 
return next.handle(req).pipe( 
tap( 
event => this.handleResponse(req, event), 
) 
) 
} 
handleResponse(req: HttpRequest<any>, event: any) { 
console.log('response log', req.url, event); 
} 
} 

Add these dependencies in app.module.ts 

import { NgModule } from '@Angular/core'; 
import { BrowserModule } from '@Angular/platform-browser'; 
import { AppComponent } from './app.component'; 
import { HttpClientModule, HTTP_INTERCEPTORS } from '@Angular/common/http'; 
import { AppHttpInterceptor } from './interceptor'; 
@NgModule({ 
declarations: [ 
AppComponent, 
], 
imports: [ 
BrowserModule, 
AppRoutingModule, 
HttpClientModule 
], 
providers: [ 
{ 
provide: HTTP_INTERCEPTORS, 
useClass: AppHttpInterceptor, 
multi: true 
} 
], 
bootstrap: [AppComponent] 
}) 
export class AppModule { } 

We have added an api call using HttpClient module in AppComponent as seen below: 

import { Component, OnInit } from '@Angular/core'; 
import { HttpClient } from '@Angular/common/http'; 
@Component({ 
selector: 'app-root', 
templateUrl: './app.component.html', 
styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
title = 'IQA'; 
constructor (private http: HttpClient) { 
} 
ngOnInit() { 
this.http.get<any>('https://api.npms.io/v2/search?q=scope:Angular').subscribe(data => { 
console.log('data from api:', data); 
}) 
} 
} 

Now when we run our app we can see that the request and response are been logged with the help of interceptor as seen below: 

An Observable does not publish records on its won't unless someone subscribes to it. So we need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

In addition to default inbuilt directives provided by Angular we can also create our own custom directive as per our requirement. To create a custom directive, we need to replace the @Component decorator with @Directive decorator. 

Example of Custom Attribute Directive to highlight the background color of text: 

import { Directive, ElementRef } from '@Angular/core'; 
@Directive({ 
selector: '[appTextHighlight]' 
}) 
export class TextHighlightDirective { 
constructor(private eleref: ElementRef) { 
eleref.nativeElement.style.background = 'yellow'; 
} 
} 

Using Custom Directive in component: 

Import the custom directive in app.module.ts and add it in declarations 

import { TextHighlightDirective } from './text-highlight.directive'; 
@NgModule({ 
declarations: [ 
TextHighlightDirective 
] 
}) 

Now we can use it in oucomponent as 

<appTextHighlight>Highligh my text</appTextHighlight>

Lazy loading is one of the important concepts of Angular Routing. Lazy Loading download the web pages in chunks instead of downloading everything altogether in a big bundle. Lazy Loading is used to load only required module with the help of property loadChildren. 

The lazy load of the modules can be done using the root routing module. This loads the modules lazily by using loadChildren method. 

 Let's load both Customer and Order feature modules lazily as below, 

const routes: Routes = [ 
{ 
path: 'customers', 
loadChildren: () => import('./customers/customers.module').then(module => module.CustomersModule) 
}, 
{ 
path: 'orders', 
loadChildren: () => import('./orders/orders.module').then(module => module.OrdersModule) 
}, 
{ 
path: ", 
redirectTo: ", 
pathMatch: 'full' 
} 
]; 

Decorators acts as metadata that is used to decorate a class. Decorators are helps in configuring the expected behavior of the class. Different Types of Decorators are 

1. Class Decorators e.g. @Component and @NgModule 

import { NgModule, Component } from '@Angular/core'; 
@Component({ 
selector: 'my-component', 
template: '<div>Class decorator</div>', 
}) 
export class MyComponent { 
constructor() { 
console.log('Hey I am a component!'); 
} 
} 
@NgModule({ 
imports: [], 
declarations: [], 
}) 
export class MyModule { 
constructor() { 
console.log('Hey I am a module!'); 
} 
} 

2. Property Decorators Used for properties inside classes, e.g. @Input() and @Output() 

import { Component, Input } from '@Angular/core'; 
@Component({ 
selector: 'my-component', 
template: '<div>Property decorator</div>' 
}) 
export class MyComponent { 
@Input() title: string; 
} 

3. Method Decorators Used for methods inside classes, e.g. @HostListener() 

import { Component, HostListener } from '@Angular/core'; 
@Component({ 
selector: 'my-component', 
template: '<div>Method decorator</div>' 
}) 
export class MyComponent { 
@HostListener('click', ['$event']) 
onHostClick(event: Event) { 
// clicked, `event` available 
} 
} 

4. Parameter Decorators Used for parameters inside class constructors, e.g. @Inject() 

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); // MyService 
} 
} 

TypeScript classes like OOPS classes has a default method called constructor which is normally used for the initialization of variables, properties. Whereas ngOnInit method is one of the Angular LifeCycle hook, especially used to define Angular bindings. Even though constructor gets called first, it is preferred to move all our Angular bindings to ngOnInit method. In order to use ngOnInit, we need to implement OnInit interface as below, 

export class App implements OnInit{ 
constructor(){ 
//called first time before the ngOnInit() 
} 
ngOnInit(){ 
//called after the constructor and called after the first ngOnChanges() 
} 
} 

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While normal Observables are unicast, Subjects are multicast. 

A Subject is like an Observable, but it has ability to multicast to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. 

import { Subject } from 'rxjs'; 
const subject = new Subject<number>(); 
subject.subscribe({ 
next: (v) => console.log(`observerA: ${v}`) 
}); 
subject.subscribe({ 
next: (v) => console.log(`observerB: ${v}`) 
}); 
subject.next(1); 
subject.next(2)

BehaviourSubject requires initialization while its creation i.e. it requires an initial value to be assigned while creating the subject and stores the current value that it emits  first time to the subscribers. 

import { Component, VERSION } from "@Angular/core"; 
import { BehaviorSubject, Subject } from "rxjs"; 
@Component({ 
selector: "my-app", 
templateUrl: "./app.component.html", 
styleUrls: ["./app.component.css"] 
}) 
export class AppComponent { 
subject$ = new BehaviorSubject("0"); 
ngOnInit() { 
this.subject$.subscribe(val => { 
console.log("Sub1 " + val); 
}); 
this.subject$.next("1"); 
this.subject$.next("2"); 
this.subject$.subscribe(val => { 
console.log("sub2 " + val); 
}); 
this.subject$.next("3"); 
this.subject$.complete(); 
} 
} 
/* 
Result 
Sub1 0 
Sub1 1 
Sub1 2 
sub2 2 
Sub1 3 
sub2 3 
*/ 

Notice how we have initialized the subject with initial value of 0 

subject$ = new BehaviorSubject("0"); 

ReplaySubject transmit old values to new subscribers when they first subscribe.

The ReplaySubject stores every value it emits in its buffer and will emit them to the new subscribers in the same order it received them. Buffer can be configured using the arguments bufferSize and windowTime bufferSize is the no. of items that ReplaySubject will keep in its buffer, bydefault this value is infinity WindowTime is the duration for which it has to keep the value in the buffer, it defaults to infinity. 

AsyncSubject only emits the latest value that too only when it completes. If it errors out then it will emit an error and will not emit any values. 

import { Component, VERSION } from "@Angular/core"; 
import { AsyncSubject, Subject } from "rxjs"; 
@Component({ 
selector: "my-app", 
templateUrl: "./app.component.html", 
styleUrls: ["./app.component.css"] 
}) 
export class AppComponent { 
subject$ = new AsyncSubject(); 
ngOnInit() { 
this.subject$.next("1"); 
this.subject$.next("2"); 
this.subject$.subscribe( 
val => console.log("Sub1 " + val), 
err => console.error("Sub1 " + err), 
() => console.log("Sub1 Complete") 
); 
this.subject$.next("3"); 
this.subject$.next("4"); 
this.subject$.subscribe(val => { 
console.log("sub2 " + val); 
}); 
this.subject$.next("5"); 
this.subject$.complete(); 
this.subject$.error("err"); 
this.subject$.next("6"); 
this.subject$.subscribe( 
val => console.log("Sub3 " + val), 
err => console.error("sub3 " + err), 
() => console.log("Sub3 Complete") 
); 
} 
} 
/* 
Result 
Sub1 5 
sub2 5 
Sub1 Complete 
Sub3 5 
Sub3 Complete 
*/ 

In the above example, all the subscribers will receive the value 5 including those who subscribe after the complete event. But if the AsyncSubject gives error, then all subscribers will receive an error notification but no value 

Angular Animations is used to implement sophisticated and compelling animations for our Angular single page web application that makes the UI/UX more interactive and attractive. The animation transition function is used to specify the changes that occur between one state and another over a period of time. It accepts two arguments: the first argument accepts an expression that defines the direction between two transition states, and the second argument accepts an animate() function. 

BrowserAnimationsModule needs to be imported from @Angular/platform-browser/animations to use animations in Angular. Let us see an example of changing the color of the button using Angular animations. 

import { Component, OnInit } from '@Angular/core'; 
import { trigger, state, style, animate, transition } from '@Angular/animations'; 
@Component({ 
selector: 'app-example', 
template: ` 
<h3>Click the button to change its color!</h3> 
<button (click)="clickMe()" [@buttonClicked]="isGreen">Toggle Me!</button> 
`, 
animations: [ // metadata array 
trigger('buttonClicked', [ // trigger block 
state('true', style({ // final CSS following animation 
backgroundColor: 'green' 
})), 
state('false', style({ 
backgroundColor: 'red' 
})), 
transition('true => false', animate('1000ms linear')), // animation timing 
transition('false => true', animate('1000ms linear')) 
]) 
// end of trigger block 
}) 
export class ExampleComponent { 
isGreen: string = 'true'; 
clickMe() { 
this.isGreen = this.isGreen === 'true'? 'false': 'true'// change in data-bound value 
} 
} 

It is recommended to use case conventions in Angular to distinguish the names of various typesAngular follows the list of the below case types. 

  • camelCase Symbols, properties, methods, pipe names, non-component directive selectors, constants use lowercase on the first letter of the item. For example, "selectedUser" 
  • UpperCamelCase (or PascalCase) Class names, including classes that define components, interfaces, NgModules, directives, and pipes uses uppercase on the first letter of the item. 
  • dash-case (or "kebab-case") The descriptive part of file names, component selectors uses dashes between the words. For example, "app-user-list". 
  • UPPER_UNDERSCORE_CASE All constants use capital letters connected with underscores. For example, "NUMBER_OF_USERS". 

Dynamic content can be displayed in the component template using content projection. The <ng-content></ng-content> tag act as a placeholder for dynamic content, then when the template is parsed Angular will replace <ng-content> placeholder tag with our content this is called content projection. 

Content projection allows a directive to use templates while still being able to clone the original content and add it to the DOM, which is a programming interface for HTML and XML documents and represents a page where programs can change the document structure, style, and content. 

Example of content projection: 

Create a component and add ng-conent tag in the template as below 
@Component({  selector'app-demo', 
template 
 <h2>Content Projection</h2> 
  Heading:  
 <ng-content></ng-content>   
Description:  
 <ng-content select="[description]"></ng-content> 
`}) 

Project the content to the component as follows: 

<app-demo> 
 <p>Projected content!</p> 
<p description>  Content Projection in Angular </p> 
</app-demo> 

Here as we had multiple ng-content tags, we add a name to one of the tags and use the same name with ng-content tag with select attribute to load the desired content in respective ng-content tag. 

If a url does not match any defined route in Angular then application throws an error, to handle these cases where url does not match any route we can make use of Wildcard route. Wildcard route will match any url that is not defined in Angular Routes and display the default component as defined in the routes.: 

Suppose we want to display PageNoFoundComponent as a wildcard route we can do it as below 

{ path: '**', componentPageNotFoundComponent } 

The @ViewChild() and @ViewChildren() decorators in Angular provide a way to access and manipulate DOM elements, directives and components. @ViewChild() is used to query one element from the DOM and @ViewChildren() for multiple elements. 

If we want to access following inside the Parent Component, use @ViewChild() decorator of Angular. 

  1. Child Component 
  2. Directive 
  3. DOM Element 

ViewChild returns the first element that matches the selector. Example: @ViewChild() 

We are using MessageComponent inside AppComponent as shown in below listing: 

import { Component, OnInit } from '@Angular/core'; 
@Component({ 
selector: 'app-root', 
template: ` 
<div> 
<h1>Messages</h1> 
<app-message [message]='message'></app-message> 
</div> 
` 
}) 
export class AppComponent implements OnInit { 
message: any; 
ngOnInit() { 
this.message = 'Hello World !'; 
} 
} 

Here MessageComponent is located inside template of AppComponent, so it can be accessed as ViewChild. 

export class AppComponent implements OnInit, AfterViewInit { 
message: any; 
@ViewChild(MessageComponent) messageViewChild: MessageComponent; 
ngAfterViewInit() { 
console.log(this.messageViewChild); 
} 
ngOnInit() { 
this.message = 'Hello World !'; 
} 
} 
  • RouterModule.forRoot(ROUTES): forRoot creates a module that contains all the directives, the given routes, and the router service itself. 
  • RouterModule.forChild(ROUTES): forChild creates a module that contains all the directives and the given routes, but does not include the router service. 

Example:

RouterModule.forRoot(ROUTES) 
import { RoutesRouterModule } from '@Angular/router'; 
export const ROUTES: Routes = []; 
@NgModule({ 
  imports: [BrowserModuleRouterModule.forRoot(ROUTES)], 
  // ...}) 
export class AppModule {} 
Example: RouterModule.forChild(ROUTES) 
import { NgModule } from '@Angular/core'; 
import { CommonModule } from '@Angular/common'; 
import { RoutesRouterModule } from '@Angular/router'; 
export const ROUTES: Routes = []; 
@NgModule({ 
  imports: [CommonModuleRouterModule.forChild(ROUTES)], 
  // ...}) 
export class ChildModule {} 
  • forRoot(): service register to entire application 
  • forChild(): service register to particular child component