Sandboxing Components with Multiple Instances
Learn how to provide an Angular service dedicated to a component, resulting in a unique service instance for each component.
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:
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
Open the
product-view.component.ts
file and declare an@Input
property namedid
to pass a unique identifier of the product you want to display:
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;}
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: ...