0

Now I started studying Angular, I was doing a simple exercise, but I had a giant doubt.

I have two components (Navbar and app), in navbar I present one that returns me the value 5. In the component app, by clicking the EXECUTE button, I want the value displayed in Navbar to 4 (-1). Is there a way to do this or make an event emitter that I pressed the EXECUTE button on the app component and thus perform a function on the navbar that allows me to reduce the number 5 to 4?

Thank you !

DEMO

Navbar component

total:any;
number = 5;

  constructor() { }

  ngOnInit() {
    this.GetNumber();
  }

  GetNumber(){
      this.total = this.number - 1;
  }
S3ck Stros
  • 325
  • 3
  • 10

2 Answers2

1

In your case, the "button" and the component are in the same .html -and in the same <router-outlet></router-outlet> you only need a template reference variable

<app-navbar #navbar></app-navbar>

<p>My APP COMPONENT</p>
<button (click)="getNumber(navbar)">Execute Function</button>

Your getNumber function has access to all the properties or functions of your navbar,e.g.

getNumber(navbar:any){
     navbar.getNumber()
     console.log(navbar.number)
  }

(*)NOTE: I use the recomender notation to named functions using camelCase and only use a named in Capitalize when we defined a Class

If you use a service, you need inject in constructor of the two components the service, see interaction using a service, The idea using a service is that one component call a method of service that emit a value and in the other component we subscribe to the service to get the value emited, see SO answer

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

It depends on the structure of your program

If they're sibling components (meaning they're instanced in the same HTML, in this case requiring a 3rd component) the best way to do this would be to use a Service with an Observable.

If there exists a parent-child relationship (one of the components instances the other one in the HTML), then you could make use of EventEmitter or ViewChild

maury844
  • 1,210
  • 15
  • 25
  • Thanks for the answer. I think in my case the best thing is to use a service. In the navbar service I created a function that gets me the total. In the app component when executing a function, I call the function created in the navbar service to update me the value, but it doesn't work ... should I be in the right direction? – S3ck Stros Jan 11 '20 at 22:51