Reputation: 711
I am implementing an angular exemple. I have an input for search in navbar component and i want to display results of search in another component but i found problem how the second component will know the value that i put it in the search input text. This my navbar.ts file :
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { RechercheService } from
'../../services/recherche/recherche.service';
@Component({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
name: string ;
listUsers;
constructor(){}
ngOnInit() {
}
search() {
let list = this.rechercheService.recherche();
if(this.name.length>2) {
let searchText = (this.name).toLowerCase();
this.listUsers= list.filter( it => {
return it.name.toLowerCase().includes(searchText);
});
if(this.listUsers.length>0){
this.sidenav.open();
}
else {
this.sidenav.close();
}
}
console.log(this.listUsers);
this.name = "";
}
}
This my navbar.html:
<div class="col-3">
<div class="input-group mb-2">
<span class="borderColor rounded-left text-center"
(click)="search()"><mat-icon class="blueIcon loupeIcon"
fontIcon="icon-search"></mat-icon></span>
<input type="text" class="form-control color"
placeholder="search" [(ngModel)]="name" >
<button class="btn-al-blue rounded-right" type="submit" >more
creteria</button>
</div>
</div>
I want to display the result of search in another component called second. how can i do it ?
Upvotes: 0
Views: 67
Reputation: 503
Create shared service for the same
// Search Control
searchFilter = new Subject<any>();
searchFiltered = this.searchFilter.asObservable();
emitSearchFilter(value) {
this.searchFilter.next(value);
}
emit from navbar component like
this.navbarService.emitSearchFilter('search keyword');
and subscribe to another component like
this.navbarService.searchFiltered.subscribe(value => {
console.log(value);
});
don't forget to unsubscribe on ngDestroy
Upvotes: 2