Ionic - Update a component's variable from another page or component

我怕爱的太早我们不能终老 提交于 2019-12-24 08:55:59

问题


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

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

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

So when I trigger toggleMenu() I change opened value

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>

So, whats my problem?

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


What have I tried

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

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


回答1:


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.

In Homepage.ts

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

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

In Menu.ts

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


来源:https://stackoverflow.com/questions/50911611/ionic-update-a-components-variable-from-another-page-or-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!