Yulian
Yulian

Reputation: 6759

How to subscribe for value changes on an input from a different module in Angular 6?

I have a header component that is located in the root (app) module. A search bar would be rendered in the header depending on the activated route.

I have friends lazy loaded module with a friends-list container component that provides a list of friends.

I want to add a search functionality to the friends-list component by subscribing to value changes on the search bar input.

How can I provide the observable of the search bar value changes to my friends-list component?

Upvotes: 2

Views: 3453

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29715

Make usage of shared service to emit the event from search bar component to friends-list component.

Create a Subject inside service, and then emit whenever the input is changed.

service.ts

public searchInputChanged : Subject<string> = new Subject<string>()

emitSearchInputChangesEvent(input) {
   this.searchInputChanged.next(input);
}

search-bar component : Simply call the method emitSearchInputChangesEvent(input)

public onChange (event) {
   this.service.emitSearchInputChangesEvent(event);
}

in friend-list component, subscribe to Subject event emitter of service.

this.service.searchInputChanged.subscribe((input)=> {
     console.log(input):
})

Upvotes: 4

Antoniossss
Antoniossss

Reputation: 32517

You can pass it as @Input to your lazy loaded component or expose input changes trough shared service

Upvotes: 1

Related Questions