I have a HeaderComponent
which displays the header in which I have a search bar, where a user when inputs something and presses enter I take the user to SearchComponent
.
I want to implement the functionality that when a user is on search page (SearchComponent
), the searchBar in header should not be visible while it should be visible on all other pages.
For this, I added variable searchShow
in HeaderComponent.ts
and by ng-if
in HeaderComponent.html
,
I show/hide the searchBar.
To change the value of searchShow
, I implemented a Header.service.ts
.
header.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class HeaderService {
showSearch = new BehaviorSubject<boolean>(true);
public showSearchObservable = this.showSearch.asObservable()
constructor(){}
}
header.component.ts
import { Component, OnInit } from '@angular/core';
import { HeaderService } from './header.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
searchShow;
constructor(
private headerService: HeaderService
) {}
ngOnInit() {
this.headerService.showSearchObservable.subscribe(
value => {
this.searchShow = value
console.log(value) ##==> prints true first time when header is initialized but does not prints anything when search component is loaded
}
)
}
}
search.component.ts
import { Component, OnInit } from '@angular/core';
import { HeaderService } from 'src/app/shared/header/header.service.js';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
constructor(
private headerService: HeaderService
) {}
ngOnInit() {
console.log(this.headerService.showSearch.value) ##==> prints true
this.headerService.showSearch.next(false)
console.log(this.headerService.showSearch.value) ##==> prints false, but this value is not emitted to header component
}
}
What am I missing? Please help. Thanks