Introduction
This is the third article in the beginner’s series of learning Angular 8 for developers who have no prior experience and little knowledge of JavaScript /typescripts. Please go through my previous labs on Angular 8 to learn the basics and setup.
In the previous articles, we have learned how communication within a component works from typescript code to HTML and vice versa using string interpolation, property and event binding, and two-way binding.
Agenda
Below is the agenda for this article.
- Components life cycle
- Life cycle hooks
- Component communication
- @Input and @Output
- Services
- Local references
- Angular Directives:
- Component Directives
- Structural Directives
- Attribute Directives
- Custom Directives
Component life cycle
A component has a lifecycle that is managed by an Angular framework. Its components are created and rendered and then checked for property changes. The framework destroys them before removing them from the DOM. Angular framework provides different life cycle hooks that run with certain functionality. It offers a way to write code on these hooks when they actually occur to achieve real-life cases.
Life cycle hooks
- ngOnchnages- It is called when a bound input property change.
- ngOnInit- It is called once the component is initialized.
- ngDocheck – it is called on every change detection runs
- ngAfterContentInit- it is called when external content is projected into the component’s view.
- ngAfterContentChecked- It is called whenever projected content has been checked
- ngAfterviewInit- It is called after component view/child view is initialized
- ngAfterViewChecked- it is called whenever view /child view is checked
- ngOnDestroy- Called just before Angular destroys the directive/component and is a very good place to clean up resources.
Ways to communicate between components
Now we have to learn using use cases in the real-life app, where these concepts are used to understand inter-component communication and also accessing variables and data outside of the component. Basically, data binding in the component from the outside.
Component communication

This is a very common use case when data communication needs to happen from parent component to child and vice versa.
- @Input and @Output
- Services
- Local references
@Input and @Output parameters
@Input is used to pass data from parent to child component meaning the child will receive data using property defined in the child component.
Let see how to implement in an example:
Parent: - Course component Child: - Course list component
Think in a way you have a property that actually holds value from parent component.In course list component (child component) lets declare a variable
- @Input() courseNameSelected : string =null;
In the course component HTML let’s get a paragraph element to display the value using string interpolation
- <p>{{ courseNameSelected }}</p>
Coming to CourseCompoenent (parent component)
- parentCourseName:string =null;
You can write any code to change value to this
- ngOnInit() {
- this.parentCourseName="Angular 8 from parent using input!!!!" ;
- }
Course Component HTML
- <div class="col-md-5">
- <app-course-list [courseNameSelected]="parentCourseName" ></app-course-list>
- </div>
@Output
@Output is used to pass data from the child to the parent component meaning parent will link a property child component and emit it through the event emitter. Parent component can call property and get data from the child.
Child: - Course list component Parent: - Course component
Course List Component
With the help of the Output parameter and EventEmitter class.
In the child component, let's define a property decorated with @Output which has a new instance of EventEmitter class of type string, there are which are a part of Angular core.
Also, a property that holds the data to be emitted from child.
- @Output () courseNameChild=new EventEmitter<string>();
- courseNameSelecedInChild:string=null;
There is a function which will be called at a button click from the child
- ondatasentParent()
- {
- this.courseNameChild.emit(this.courseNameSelecedInChild);
- }
- <button class="btn btn-success" (click)="ondatasentParent()">Send to Parent Compoent</button>
This is the HTML mark-up for this.
Parent component set up to receive the data emitted from the child.
A string property to receive the data emitted from child.
- childCourseName:string=null;
a method to receive data from $event.
- recievefromChild($event:string){
- this.childCourseName=$event;
- }
HTML mark-up
This is very important to understand that courseNameChild property is defined in child with @Output decorator which is hooked with a function which actually receives data with $event as a parameter. Here you can see all the previous implementation of property binding, event binding and string interpolation .
- <div class="col-md-5">
- <app-course-list [courseNameSelected]="parentCourseName" (courseNameChild)="recievefromChild($event)"></app-course-list>
- </div>
- <p>{{ childCourseName }}</p>
On a click of the button
The parent has received a string from the child and displays it.

Angular Services
Services are nothing but a class with a reusable piece of code that serves a unique purpose and also decouples some business logic away from the component. It modularises the app code by separating out the responsibilities and keep component lean. Services use dependency injection to be utilized across the component by getting injected in the constructor. We will take a deeper look later in the course.
Basically, it will show another way to communicate between components.
Taking an example of logging functionality which is common to every component. Rather reparenting the logging code in every component, a logging service will be created which later can be injected in component
I have created a service named course.service.ts
- import { Injectable } from '@angular/core';
- import { Course} from './course.model';
- @Injectable({providedIn:'root'})
- export class CourseService
- {
- courses: Course[]=[
- new Course('Angular 8 ', 'Learning Angular 8 !!!'),
- new Course('React Js', 'Learning react !!!'),
- new Course('webapi Core 8 ', 'Learning asp.net core !!!'),
- new Course('Azure', 'Learning Azure !!!'),
- new Course('Mongo DB', 'Learning MongoDB !!!')
- ];
- getCourses()
- {
- return this.courses.slice();
- }
- }
This service is very simple example service which has method and it returns list of course with name and description in it.
Now we need to know how it can be used.
- import { Component, OnInit , Input} from '@angular/core';
- import {CourseService} from '../course.service';
- import {Course} from '../course.model';
- @Component({
- selector: 'app-course-list',
- templateUrl: './course-list.component.html',
- styleUrls: ['./course-list.component.css']
- })
- export class CourseListComponent implements OnInit {
- courses: Course[]=[];
- statusMessage:string = "No course found!!!!";
- result : number=10;
- isDisabled= false;
- isData=false;
- courseName="";
- constructor(private courseService:CourseService) {
- setTimeout(() => {
- this.isDisabled=true;
- }, 5000);
- }
- ngOnInit() {
- this.courses= this.courseService.getCourses();
- console.log(this.courses);
- }
- constructor (private courseService:CourseService) { }
You can inject the service which is required in the component constructor by informing angular we need the service instance here in this component and once you have the service instance available you can call the require method to communicate using this service.
Providers for service: registrations
Service needs to be registered to at least one provider of any service you are going to use. Your register providers are in the metadata of the service
- @Injectable() decorator- Register a provider with the root injector for your service by including provider metadata in the @Injectable()
@Injectable({ providedIn: 'root', })
Registering service at the root level, a single, shared instance of service is created and injects it into any class that asks for it.
- @NgModule()– Register a provider with a specific NgModule, the same instance of a service is available to all components in that NgModule.
@NgModule({providers: [ service1, service2], ... })
- @Component()metadata- Register a provider at the component level, a new instance of the service with each new instance of that component.
- @Component({
- selector: 'app-test',
- templateUrl: './test.component.html',
- providers: [ Service1]
- })
Cross Component Communication using Services
It will be very easy with services to communicate by using event emitter and services.
Let’s understand with a user case and demo.
There are two components course list and course where you want to send course name on click of button in course list component using services.
Let’s create a service course service which will help in commutation between these components.
Course Service
- import { Injectable , EventEmitter} from '@angular/core';
- import { Course} from './course.model';
- @Injectable({providedIn:'root'})
- export class CourseService
- {
- courseSelected=new EventEmitter<Course>();
- courseNameSelected=new EventEmitter<string>();
- courses: Course[]=[
- new Course('Angular 8 ', 'Learning Angular 8 !!!'),
- new Course('React Js', 'Learning react !!!'),
- new Course('webapi Core 8 ', 'Learning asp.net core !!!'),
- new Course('Azure', 'Learning Azure !!!'),
- new Course('Mongo DB', 'Learning MongoDB !!!')
- ];
- getCourses()
- {
- return this.courses.slice();
- }
- }
In course service, lets create a string property which holds new event emitter of type string.
- courseNameService: string =null;
- ngOnInit() {
- this.courses= this.courseService.getCourses();
- this.courseNameSelecedInChild="Angular 8 from child compoement !!!!";
- this.courseNameRef= "Angular 8 from child compoement with reference !!!!"
- this.courseNameService="Angular 8 from child compoement using service !!!!"
- }
ngOnInit() , I have assign a string which I want to send to a course component, which is the parent one.




Sourav Kumar DasPosted Dec 26, 2019, 12:57 AM
Nice and useful article. Thanks for sharing.
Ankur MistryPosted Dec 23, 2019, 10:05 PM
Great thank you for sharing