viewProvider

We know that the decorator functions of @Component take object and this object contains many properties. Then we will learn about the properties of viewProvider in this article.

The viewProviders property allows us to make providers available only for the component’s view.

When we want to use a class in our component that is defined outside the @Component () decorator function, then, first of all, we need to inject this class into our component, and we can achieve this with the help of the "viewProvider" property of a component.

Use the following code in app.component.ts file.

app.component.ts

import { Component, Injectable } from '@angular/core';

class MyProvider {
  constructor() {
    console.log("provider property");
  }
  VarMyProvider = "VarMyProvider";
}

class MyProvider1 {
  VarMyProvider1 = "VarMyProvider1";
  constructor() {
  }
  getString(name) {
    console.log("provider property1" + name);
  }
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  viewProviders: [MyProvider, MyProvider1]
})
export class AppComponent {
  constructor(public obj: MyProvider, public obj1: MyProvider1) {
    obj1.getString(" SahosoftTutorials.com");
    console.log(obj.VarMyProvider);
    console.log(obj1.VarMyProvider1);
  }

  title = 'app';
}

In this, we have created two classes, like : "MyProvider" and "MyProvider1". If we want to use these classes in our component, first inject the name of your class in the Provider.

viewProviders:[MyProvider, MyProvider1]  

Then, create an object into the constructor.

constructor(public obj:MyProvider, public obj1:MyProvider1)

So with the help of these objects (obj, obj1), we can use the methods of the MyProvider class and MyProvider1 in our component.

This will be the output of the above code.

sahosoft-Tutorials-viewProvider