Angular / Ionic get changes done on ion-toggle on parent component

Issue

I have a toggle button on a child component of my Ionic/Angular project.

In the child component I have:

<ion-buttons slot="end">
    <ion-toggle [(ngModel)]="enabled" (ionChange)="toggleEnabled()"></ion-toggle>
</ion-buttons>

In the parent component I have:

<child-component></child-component>

In the parent .ts:

enable: boolean = false;

toggleEnabled() {
    // code here executed when the child toggle button is changed.
}

How can I leave the ion-toggle button in the child component but get changes and execute toggleEnabled() which is on the parent component

Solution

You need to setup the Output into your child class.

Documentation about this: https://angular.io/guide/inputs-outputs

In Angular

.ts

import { Output, EventEmitter } from '@angular/core';

class ChildComponent {
  @Output() outputName = new EventEmitter<any>();
public enabled: boolean; // I guess 'enabled' is a boolean into the child's .ts

enableButton(): void {
  this.outputName.emit(this.enabled); // here you put the output from child to parent 
}


}

.html

<ion-buttons slot="end">
    <ion-toggle (click)="enableButton()" [(ngModel)]="enabled"></ion-toggle>
</ion-buttons>

then you will include into parent’s HTML file the child element like this:

<child-component (outputName)="toggleEnabled($event)"></child-component>

Parent’s .ts

toggleEnabled(isEnabled: boolean): void {

// do something with 'enabled' data

}

Answered By – Diego Lai

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published