1
votes

I am new to Ionic/Angular and I was hoping for some help.

I want to output the device battery level on the screen using the Capacitor Device plugin but I can't work out how. I have managed to log it in the console correctly but don't know what I need to do display it on the front end.

My code on home.page.ts is:

import { Component, OnInit } from '@angular/core';
import { Device } from '@capacitor/device';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {

  constructor() { }

  batteryInfo = async () => {
    const batteryInfo = await Device.getBatteryInfo();
    const batteryLevel = batteryInfo.batteryLevel;
    console.log('Battery level: ', batteryLevel*100, '%');
    return batteryLevel;
  }

  ngOnInit() {
    this.batteryInfo();
  }
}

But how do I now display that in my <ion-label>{{ ? }}</ion-label> on the front end?

I did try <ion-label>{{ batteryLevel }}</ion-label> but it just outputs

[object Promise]

2

2 Answers

0
votes

You're not a million miles off. You need to declare a variable and then call that variable in the HTML file. So in your case:

import { Component, OnInit } from '@angular/core';
import { Device } from '@capacitor/device';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {

  public battery: number;

  constructor() { }

  async batteryInfo() {
    const batteryInfo = await Device.getBatteryInfo();
    this.battery = batteryInfo.batteryLevel;
  }

  ngOnInit() {
    this.batteryInfo();
  }
}

And with your HTML file, using Ionic:

<ion-label>{{ battery }}</ion-label>
-4
votes

import { Device } from '@capacitor/device'; this package is not working on firefox browser enter image description hereenter image description here