So I'm trying to toggle an element in a separate component, while firing the function to change the boolean value from the ionic tabs component so far I have this.
//App.module.ts - Cut down for the sake of brevity
import { AppGlobals } from './globals';
@NgModule({
providers: [AppGlobals]
})
//Globals.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import 'rxjs/add/operator/startWith';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class AppGlobals {
// use this property for property binding
public showSearch:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
setShowSearch(search){
this.showSearch.next(search);
console.log(search);
}
}
// Tabs.ts
import { AppGlobals } from '../../app/globals';
constructor(private _appGlobals: AppGlobals) {
this._appGlobals.showSearch.subscribe(value => this.search = value);
}
toggleSearch() {
this.search = !this.search;
console.log(this.search);
}
//Tabs.html
(ionSelect)="toggleSearch();"
//This is on some HTML within the the separate component
<div *ngIf="search" [ngClass]="{'slideInRight':showSearch, 'fadeOut':!showSearch}" class="search-filters animated">
However this doesn't appear to be working, I'm toggling the value however the global "showSearch" seems to stay the same. What is the correct way of achieving the toggle of the element across the two components?
Any help at all is very appreciated.
your Tabs.ts
will emit an event when toggleSearch()
method call
toggleSearch() {
this.search = !this.search;
console.log(this.search);
this._appGlobals.showSearch.next(this.search);
}
in another component
import { AppGlobals } from 'path/to/app/globals';
@Component({...})
export class SubComponent implements OnInit {
showSearch: boolean = false;
constructor(private _appGlobals: AppGlobals) {
}
ngOnInit() {
this._appGlobals.showSearch.subscribe(value => this.showSearch = value);
}
}
SubComponent template
<div *ngIf="showSearch">content</div>