First to demonstrate Service in Angular we need to create a demo project using angular CLI and make a child component and a service using the Angular CLI
ng new ServiceDemo ng g c child ng g s date
Now modify the date.service.ts as per below.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DateService { showTodayDate() { return new Date(); } }
Modify app.component.html as below :
Todays Date time displayed in Parent Component : {{todaysDate}} <app-child></app-child>
Modify app.component.ts as below :
import { DateService } from './date.service'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ title = 'ServiceDemo'; todaysDate; constructor(private dateService: DateService) {} ngOnInit() { this.todaysDate = this.dateService.showTodayDate(); } }
Modify child.component.html as below :
<p>Hi This is child component!</p> Todays date time displayed in child component{{todaysDate}}
Modify child.component.ts as below :
import { Component, OnInit } from '@angular/core'; import { DateService } from '../date.service'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { todaysDate; constructor(private dateService: DateService) {} ngOnInit() { this.todaysDate = this.dateService.showTodayDate(); } }
Note : We need to add the service in the providers section of app.module.ts file as below :
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { ChildComponent } from './child/child.component'; import { DateService } from './date.service'; @NgModule({ declarations: [ AppComponent, ChildComponent ], imports: [ BrowserModule ], providers: [DateService], bootstrap: [AppComponent] }) export class AppModule { }
Output will look like below :