Coding With Fun
Home Docker Django Node.js Articles FAQ

Angular 2 relies on injection

May 08, 2021 Angular2

Table of contents


Dependency injection is a powerful model for managing code dependencies.

Dependency injection is a design pattern that passes objects as dependencies in different components of an application. I t creates a new class instance and its required dependencies. Dependency injection is stimulated into the framework and can be used anywhere.

When using dependency injection, you must keep the following in mind:

  • The injector mechanism maintains service instances and can be created using providers.

  • Providers are a way to create services.

  • You can register the provider with the injector.


The following example describes the use of dependency injection in Angle 2:

<!DOCTYPE html>
    <title>Angular 2 Dependency Injection</title>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}}
            .then(null, console.error.bind(console));

The above code includes the following configuration options:

  • You can configure index files using the .html version. SystemJS converts TypeScript to JavaScript before running the application using the transpiler option.

  • If you don't translate to JavaScript before you run your application, you may see compiler warnings and errors hidden in your browser.

  • TypeScript generates metadata for each class of your code when you set the emitDecorator Metadata option. If you do not specify this option, a large amount of unused metadata is generated, which affects the file size and the application runtime.

  • Angular 2 includes packages from the app folder, Chinese will have a .ts extension.

  • Next it loads the main component file from the application folder. If the primary component file is not found, it displays an error in the console.

  • When Angula called the boot function in main.ts, it reads the Company metadata, finds the "app" selector, finds an element label named app, and loads the application between those tags.

Let's create TypeScript (.ts) files and save them in the app folder.

import {bootstrap} from 'angular2/platform/browser';     //importing bootstrap function
import {AppComponent} from "./fruit-component";          //importing component function

import {Component} from 'angular2/core';
import {MyListComponent}  from './play-component';

//@Component is a decorator that uses configuration object to create the component and its view.
  selector: 'my-app',   //The selector creates an instance of the component where it finds 'my-app' tag in parent HTML
  directives:[MyListComponent]  //'MyListComponent' is the root component of fruits that governs child components
export class AppComponent { }
import {Component} from "angular2/core";
import {FruitService} from "./fruits.service";
import {Fruits} from "./fruits";
import {OnInit} from "angular2/core";

   selector: "my-list",
   template: ` List of Fruits<br>
      <li *ngFor="#list of fruits">  //The NgFor directive instantiates a template once per item from an iterable
         {{}} - {{ }}
   providers: [FruitService]  //providers are part of @Component metadata

//The 'MyListComponent' should get list of fruits from the injected 'FruitService'
export class MyListComponent implements OnInit {
   public fruits : Country[];

   //Using constructor, call the _fruitService and populate the fruits list
   constructor(private _fruitService: FruitService) {}

      this._fruitService.getContacts().then((fruits: Country[]) => this.fruits = fruits);

   //The 'ngOnInit()' hook is called when done with creating the component and evaluated the inputs
import {Injectable} from "angular2/core";
import {COUNTRIES} from "./fruits.lists";

//It is used for meta data generation and specifies that class is available to an injector for instantiation

//'FruitService' exposes 'getContacts()' method that returns list of data
export class FruitService {
   getContacts() {
      return Promise.resolve(COUNTRIES); // takes values from fruits.lists.ts file
import {Fruits} from "./fruits";

//storing array of data in Fruits
export const COUNTRIES: Fruits[] =[
   {"id": 1, name :"Apple"},
   {"id": 2, name: "Grapes"},
   {"id": 3, name: "Orange"},
   {"id": 4, name: "Banana"}
export interface Fruits{
   id: number;
   name: string;


Let's take the following steps to see how the code above works:

  • Save the HTML code above as an index .html file, as we created in the Environment section, and use the application folder above that contains the .ts file.

  • Open the terminal window and enter the following command:

    npm start
  • Later, the browser tab should open and display the output, as shown below.

Or you can run the file in another way:

  • Save the HTML code above as angular2_dependency_injection.html file in the server root folder.

  • Open this HTML file as http://localhost/angular2_dependency_injection.html and display the output as shown below.

Related tutorials

HTML tutorial