Ionic - 从另一个页面或组件更新组件的变量 [英] Ionic - Update a component's variable from another page or component

查看:236
本文介绍了Ionic - 从另一个页面或组件更新组件的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Ionic3中创建自定义菜单,当用户点击该hamburguer图标时,它需要添加到元素 #menu open class,我正在尝试用 ngClass

I'm trying to create a custom menu in Ionic3, when the user clicks in that hamburguer icon, it needs to add to the element #menuan open class, I'm trying to do this with ngClass

问题是这个图标在我的菜单组件之外,这个图标在我的页面中 home-user

The problem is that this icon, is outside of my menu component, this icon is in my page home-user

打开时,我的菜单看起来像下一张图片,所以我无法使用离子的默认菜单

When opened, my menu looks like this next image, so I can't use the default menu from ionic

所以我的组件 menu 有一个名为的变量已打开,此变量决定了我的菜单元素的类

So I have my component menu that has an variable named opened, and this variable decides the class of my menu element

Menu.ts

@Component({
    selector: 'menu',
    templateUrl: 'menu.html',
})

export class MenuComponent {

    opened: boolean = true;

    constructor() {
    }

    toggleMenu() {
        this.opened = !this.opened;
    }
}

所以当我触发 toggleMenu时()我更改已打开

我在组件页面中触发此功能工作正常

I trigger this function in my component page and works correctly

Menu.html

<div id="menu" [ngClass]="opened ? 'open' : ''">
    <a class="menu-item" href="#">Sair</a>
    <ion-icon (click)="toggleMenu()" id="toggleMenu" name="close"></ion-icon>
</div>






那么,我的问题是什么?

如何从我的 toggleMenu() > home-user.html 页面,还有一个按钮,此按钮应更改已打开的值变量

How can I call this toggleMenu() from, for example, my home-user.html page, that also has an button and this button should change the value of opened variable

我尝试了什么

我试图创建一个我的 menu.module.ts 中的函数在菜单中触发 toggleMenu()函数。 ts

I tried to create a function in my menu.module.ts that trigger the toggleMenu() function in menu.ts

Menu.module.ts

@NgModule({
    declarations: [
        MenuComponent,
    ],
})
export class MenuComponentModule {

    constructor(public menuComponent: MenuComponent) {

    }

    toggleMenu() {
        this.menuComponent.toggleMenu()
    }
}

但是为了安慰这些值,我注意到<$ c $的值c>打开从组件调用和从我的页面调用时有所不同

But consoling the values, I notice that the value of opened is different when calling from component and when calling from my page

推荐答案

我建议使用 活动 模块离开。

I recommend to use Events module in ionic.

此模块生成的事件在整个应用程序上全局传播。

An event generated by this module propagates globally over whole app.

您可以像使用它一样使用它以下。

you can use it like the below.

Homepage.ts

import { Events } from 'ionic-angular';
//skip wrapping component
constructor(public events: Events) {}

onMenuClicked(){
  this.events.publish('toggleMenu')
}

Menu.ts

import { Events } from 'ionic-angular';
//skip wrapping component
constructor(public events: Events) {
  events.subscribe('toggleMenu', () => {
    this.opened = !this.opened
  });
}

这篇关于Ionic - 从另一个页面或组件更新组件的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆