SpaceDogCS
SpaceDogCS

Reputation: 2968

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

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

enter image description here

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

enter image description here

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

Upvotes: 1

Views: 3525

Answers (1)

Hyuck Kang
Hyuck Kang

Reputation: 1789

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

Upvotes: 7

Related Questions