Ben Clarke
Ben Clarke

Reputation: 17

Passing data between components issue

I am trying to pass information from one component to another and information from that component back again.

I am just wondering what is the best way to do this.

I have tried to use an EventEmitter but seem to be coming across some issues:

There is a Input box that on every key press I want it to call the other component with the current value in the box:

HTML:

<input type="text" #box (keyup)="searchValueChanged(box.value)"  class="form-control" placeholder="Search for an Application..."/>

JS:

@Output() messageEvent = new EventEmitter<string>();

searchValueChanged(value:string) {
  this.messageEvent.emit(value);
  console.log(value);
}

Then in the other component I am trying to receive the message:

HTML:

<app-menu-top (messageEvent)="receiveMessage(value)"></app-menu-top>

JS:

receiveMessage(value) {
  this.message = value;
  console.log(this.message);
}
  1. Is this the best way for me to be passing data?
  2. How come 'value' seem to be undefined (empty)?

Upvotes: 0

Views: 276

Answers (2)

Jaime
Jaime

Reputation: 498

From Angular docs, Recipes for common component communication scenarios

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

Its normal to use this style to pass data from one component into another. One solution also can be to use singleton service and observable into it.

What about undefined - change value into the $event

<app-menu-top (messageEvent)="receiveMessage($event)"></app-menu-top>

Upvotes: 1

Related Questions