Search code examples
ionic-frameworkionic4

Is there a way to set only one mode on a component globally in Ionic 4?


I want to only have one look for my ion-button component, no matter what the platform is. I know I can use the mode property:

<ion-button mode="ios">My button</ion-button>

but is there a way to set this globally for the ion-button, so I don't have to do this every time?


Solution

  • I don't think there is an out of the box solution to override every ion-button's mode. There is however a global config option to set the mode of the whole app: https://ionicframework.com/docs/angular/config

    A solution for you could be to create your own custom angular component containing a single ion-button element. You would need to set inputs and outputs accordingly to your needs and the ion-button component inputs but you would be able to definitely set the mode and instead of , you would just use everywhere in your app.

    It is probably overkill if the only thing that you require is to set the platform mode, but if you have more customization that you wish to reuse throughout your app, you could have something like this in your ts file:

    import { Input, Output, EventEmitter } from '@angular/core';
    import { Component, OnInit } from '@angular/core';
    
    @Component({
     selector: 'my-button',
     templateUrl: './my-button.component.html',
     styleUrls: ['./my-button.component.scss'],
    })
    export class YourButtonComponent implements OnInit {
    
     @Input() public label: string;
     /* you can also define defaults values here */
     @Input() public isDisabled: boolean = false;
     @Input() public icon: string;
     /* define more inputs if necessary: fill, expand, color.... */
    
     @Output() public buttonClicked = new EventEmitter();
    
     constructor() { }
    
     ngOnInit() {}
    
     buttonClick() {
        this.buttonClicked .emit(true);
     }
    
    }
    

    In your html you would have:

    <ion-button [disabled]="isDisabled" (click)="buttonClick()" mode="ios">
        <ion-icon slot="start" [name]="icon"></ion-icon>
        <ion-label>{{label}}</ion-label>
      </ion-button>
    

    After importing your custom component in your page module, you can use it:

    <my-button [label]="'Add something'" [icon]="'add'" (buttonClicked)="doSomethingWhenClicked()"></my-button>
    

    The mode is on the component itself and you can add a lot more customization reusable everywhere in your app.