DEV Community

Cover image for Angular Inter-Component Communication
Matthew Davis
Matthew Davis

Posted on • Originally published at matthewdavis.io

Angular Inter-Component Communication

Communicating between components can be a challenging concept to grasp. Fear not, I will show you how to effectively communicate between your components using a simple "service" design pattern.

At a high level the service class will hold our variables. When we want to access, or modify, these variables we will simply use dependency injection and "inject" our service class into the component class(es) that need to access this information.

Live Demo https://ng-byexamples-component-comms.herokuapp.com/

The Service

A service is nothing more than a class that contains reusable logic that you want to share between other services and components.

import { Injectable }  from '@angular/core';
import { FormControl } from '@angular/forms';

@Injectable({
    providedIn: 'root'
})
export class MyServiceService {

    /**
     * Holds the current page name.
     *
     * @type {string}
     */
    public currentPage: string;

    /**
     * Holds the value of the <input>'s.
     *
     * @type {number}
     */
    public someNumber: number = 0;

    /**
     * FormControl to hold the value of the <input> on each components page.
     * @type {FormControl}
     */
    public formControl: FormControl = new FormControl('');

    public constructor() {

        //
        // Subscribe to the formControl's changes and update the service value.
        //
        this.formControl.valueChanges.subscribe(value => this.someNumber = value);

    }

}

This is what the service class looks like based on the needs for this demo. You can add ass many properties as you want!

The Component

Our component will use dependency injection to inject our MyServiceService class instance and because we're making it public we can access it's properties and methods from within our template.

The Component Class

import { Component }        from '@angular/core';
import { MyServiceService } from '../my-service.service';

@Component({
    selector: 'app-page1',
    templateUrl: './page1.component.html',
    styleUrls: [ './page1.component.scss' ]
})
export class Page1Component {


    /**
     * By passing the service class to the constructor dependency injection
     * will automatically instantiate it for us.
     *
     * @param {MyServiceService} myServiceService class instance reference.
     */
    public constructor(public myServiceService: MyServiceService) {

    }

}

The Component Template

<h1>Page 1 Component</h1>

<p>Enter a value below and you will see it update in the footer!</p>

<label>Enter some Number:</label>
<input [formControl]="myServiceService.formControl">

As you can see by using [formControl]="myServiceService.formControl" we are binding the <input> attribute [formControl] to the FormControl instance from our service class.

See also

This tutorial is accompanied by a live demo and github repository.

Questions or Concerns?Contact me at matthew@matthewdavis.io!

GitHub logo mateothegreat / ng-byexamples-component-communication

Communicate between components using a Service.

NgByexamplesComponentCommunication

This project was generated with Angular CLI version 8.3.17.

Development server

Run ng serve for a dev server. Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.

Code scaffolding

Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.

Build

Run ng build to build the project. The build artifacts will be stored in the dist/ directory. Use the --prod flag for a production build.

Running unit tests

Run ng test to execute the unit tests via Karma.

Running end-to-end tests

Run ng e2e to execute the end-to-end tests via Protractor.

Further help

To get more help on the Angular CLI use ng help or go check out the Angular CLI README.

Top comments (0)