In this article, I am going to demonstrate that how we can use angular providers to add custom class and its properties and functions into another component.
Example:
Step1: First we will create a new typescript file with “.ts” extension which represents our custom class.
// we have to export keywork before class name because we will use this class into extenal component
export class myemp {
empname: string;
empsalary: number;
address : string;
}
Step 2: Create a new component “useclass”.
ng g c useclass
Step 3: add the following code into useclass.component.ts.
import { Component, OnInit } from '@angular/core';
// add reference of custom class
import { myemp } from '../models/emp';
@Component({
selector: 'app-useclass',
templateUrl: './useclass.component.html',
styleUrls: ['./useclass.component.css'],
// Add providers and pass reference of myemp class
providers: [myemp]
})
export class UseclassComponent implements OnInit {
// create object of newly added class
constructor(public empobj : myemp) { }
ename: string;
esalary: number;
address: string;
ngOnInit() {
// initilze myemp class properties and assign into component properties
this.ename = this.empobj.empname ='Yogesh Sharma';
this.empobj.empsalary = 1000;
this.empobj.address='Pratap Nagar , Jaipur';
// this.ename = this.empobj.empname;
this.esalary = this.empobj.empsalary;
this.address = this.empobj.address;
}
}
Step 4: add the following code into useclass.component.html.
<p>
useclass works!
</p>
<span>{{ ename }}</span>
<span>{{ esalary }}</span>
<span>{{ address }}</span>
Step 5: Add reference of the useclass component into app.component.html
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<ul>
<app-useclass></app-useclass>
Step 6: Run program code
ng serve --open
Output
