Search⌘ K

Sandboxing Components with Multiple Instances

Explore how to sandbox Angular components by providing multiple service instances at the component level. Understand how to create local caches, inject services within services, and manage unique data for each component instance. Learn to wire components and services for isolated state and discover the impact of provider hierarchies on service instance sharing.

We'll cover the following...

When we provide a service through the component injector and inject it into the component’s constructor, a new instance is created every time the component is rendered on the page. It can come in handy in cases such as when we want to have a local cache service for each component. We will explore this scenario by transforming our Angular application so that the product list displays a quick view of each product using an Angular service:

  1. Run the following command inside the src\app\products folder to create a new Angular component for the product view:

Note: The command below is for creating a component on the local machine using the Angular CLI.

ng generate component product-view
Command to create a component
  1. Open the product-view.component.ts file and declare an @Input property named id to pass a unique identifier of the product you want to display:

TypeScript 4.9.5
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-product-view',
templateUrl: './product-view.component.html',
styleUrls: ['./product-view.component.css']
})
export class ProductViewComponent {
@Input() id = -1;
}
  1. Run the following Angular CLI command inside the src\app\products\product-view folder to create an Angular service that will be dedicated to the product view component:

...