javascript - How to share a variable and track it's change in multiple components in angular v4 ts -


i have 3 components: a, b , c: component has variable x:number , function increase value of variable. here code snippet.

export class acomponent{    x:number = 1;    inc():void    {       x += 1;    } } 

both b , c components have template displays value of variable x. question how call inc() function in component b , change value in both templates of b , c?

e.g when click button in b , increase value of x 1 2, both b , c should display 2.

the easiest create service:

import { injectable } '@angular/core';  @injectable() export class myservice {      private _x:number = 0;      x():number {                 return this._x;     }      inc() {        this._x = this._x + 1;     } } 

then, of other components, inject service , use it:

export class acomponent {      constructor(private _svc:myservice) { }      dosomething() {         // read value         console.log(this._svc.x);          // increase         this._svc.inc();     }  } 

remember add service app.module.ts in providers section.

this specific communication strategy can found at: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

for other methods of communication between componets, check: https://angular.io/docs/ts/latest/cookbook/component-communication.html#


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -