使用服务使用单独的组件切换ngIf?

时间:2017-02-09 15:36:38

标签: javascript angular typescript ionic-framework angular-ng-if

所以我试图在一个单独的组件中切换一个元素,同时触发函数来改变离子选项卡组件的布尔值到目前为止我有这个。

// App.module.ts - 为了简洁而减少

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();"

//这是在单独组件

中的某些HTML上
<div *ngIf="search" [ngClass]="{'slideInRight':showSearch, 'fadeOut':!showSearch}" class="search-filters animated">

然而,这似乎不起作用,我正在切换值,但全局“showSearch”似乎保持不变。在两个组件之间实现元素切换的正确方法是什么?

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Tabs.ts方法调用

时,toggleSearch()会发出一个事件
toggleSearch() {
    this.search = !this.search;
    console.log(this.search);
    this._appGlobals.showSearch.next(this.search);
}

在另一个组件中

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);
    }

}

子组件模板

<div *ngIf="showSearch">content</div>