Reputation:
Hello i use this git to enable dark mode to my project. https://github.com/ionic-team/ionic-conference-app
It works but i want to put the toggle button in a page and not to app.component.html
Dark theme works like that.
Toggle button in app.component.html
<ion-app [class.dark-theme]="dark">
<ion-split-pane contentId="main-content">
<ion-item>
<ion-icon slot="start" name="moon-outline"></ion-icon>
<ion-label>
Dark Mode
</ion-label>
<ion-toggle [(ngModel)]="dark"></ion-toggle>
</ion-item>
</ion-split-pane>
</ion-app>
Set dark parameter to false so it could change in toggle
export class AppComponent implements OnInit {
dark = false;
constructor(
So this works. And in case it works but only in the page not the whole project goes on dark only the page that i set the toggle. So i think that i have to pass parameter to app.component.ts?
I have added a new service Global Service
global.service.ts
import {BehaviorSubject} from "rxjs";
export class GlobalService {
public darkModeToggleState = new BehaviorSubject(false);
constructor(){}
}
app.component.ts
import { GlobalService } from './services/global.service/global.service';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
providers: [GlobalService],
})
export class AppComponent implements OnInit {
dark;
app.component.html that will change the class to dark
<ion-app [class.dark-theme]="dark">
<ion-router-outlet></ion-router-outlet>
</ion-app>
somepage.html
<ion-toggle *ngIf="index === 5" [(ngModel)]="dark" (ionChange)="darkToggled($event)"></ion-toggle>
somepage.ts
import { GlobalService } from '../../services/global.service/global.service';
constructor(){}
darkToggled(event){
this.globalSrvc.darkModeToggleState.next(event.target.chacked)
}
Upvotes: 0
Views: 438
Reputation: 1934
You can setup a BehaviourSubject to keep track of this toggle. Do it like this.
In your component html file
<ion-toggle [(ngModel)]="dark" (ionChange)="darkToggled($event)"></ion-toggle>
In your component .ts file
constructot(private globalSrvc:GlobalService){}
darkToggled(event){
this.globalSrvc.darkModeToggleState.next(event.target.checked)
}
New service file, global.service.ts
export class GlobalService {
public darkModeToggleState = new BehaviorSubject(false);
constructor(){}
}
In your app.component.ts
dark;
constructor(private globalSrvc:GlobalService){
this.globalSrvc.darkModeToggleState.subscribe(value=>{
this.dark = value
}
}
With this, you can add the dark mode toggle to multiple components, anywhere.
Upvotes: 0