ionic-framework - 如何在 Ionic 的应用程序组件中触发自定义事件?
问题描述
在ionic
项目中,我想更改变量showSearchBox
dynamically
,这就是原因。我使用了一个searchBox
由另一个组件触发但searchBoxShow()
从未调用过的自定义事件。那么我该如何解决这个问题,以便我可以动态触发一个函数,该函数app.component
将动态更新变量searchBox
。
这是我的app.component.html
代码。
<ion-app>
<ion-router-outlet style="margin-top: 50px; bottom: 0px;" *ngIf="showSearchBox" (searchBox)="searchBoxShow()"></ion-router-outlet>
<ion-router-outlet *ngIf="!showSearchBox" (searchBox)="searchBoxShow()" ></ion-router-outlet>
</ion-app>
以及other.component.ts
.
@Output('searchBox') showSearchBox = new EventEmitter();
ionViewDidEnter() {
this.showSearchBox.emit();
}
解决方案
创建事件服务。在 EventService.ts 中:
export class EventService {
private dataObserved = new BehaviorSubject<any>('');
currentEvent = this.dataObserved.asObservable();
constructo(){}
publish(param):void {
this.dataObserved.next(param);
}
}
从示例 page1 发布事件:
constructor(public eventService:EventService){}
updatePost(value){
this.eventService.publish('show:searchbar');
}
在 app.component.ts 中:
constructor(public eventService:EventService){
eventService.currentEvent.subscribe(value=>{
if(value=='show:searchbar'){
//do something eachtime event is emited
}
});
}
推荐阅读
- javascript - vue 组件中的 d3.js - 如何将鼠标事件挂钩到元素?
- scala - 如何将元素存储在循环内的 Scala List 中?
- c# - automapper 将 typeof 对象转换为枚举
- ios - 在相同类型的 3 个单独的静态 TableViewCell 上设置内容
- php - 来自数据库的 Symfony4 数据不是 utf8 编码的
- python - 如何以编程方式访问流编辑器?
- java - 如何正确使用具有多个值的枚举
- angular - 如何在 flickr Rest API 上使用照片 url 获取照片信息?
- java - RxAndroidBle - 长写和收听通知特性
- json - 多行字符串作为 Json 中的值