DEV Community

Discussion on: Enabling Dark Mode On Websites Based On Surrounding Light

Collapse
 
msumanphexaware profile image
MsumanP-hexaware

How can i implement the same in angular ?
I tried but Its giving error.

Collapse
 
ananyaneogi profile image
Ananya Neogi

This is just plain JavaScript so it should work. Can you elaborate what error it is?
Maybe it's something specific to angular and not related to this particular bit of code.

Collapse
 
msumanphexaware profile image
MsumanP-hexaware • Edited

I am getting error like Property 'AmbientLightSensor' does not exist on type 'Window' & Cannot find name 'AmbientLightSensor'.

My Code:
if (window.AmbientLightSensor) {
const sensor = new AmbientLightSensor();
sensor.onreading = () => console.log(sensor.illuminance);
sensor.onerror = event => console.log(event.error.name, event.error.message);
sensor.start();
}

Thread Thread
 
ananyaneogi profile image
Ananya Neogi

You need to extend the existing Window interface to tell it about this new property.
So, before your class implementation add this code -

declare global {
    interface Window {
        AmbientLightSensor: any;
    }
}

Then you can add your AmbientLightSensor code in the following way -

        if (window.AmbientLightSensor) {
            const sensor = new window.AmbientLightSensor();
            sensor.onreading = () => console.log(sensor.illuminance);
            sensor.onerror = event => console.log(event.error.name, event.error.message);
            sensor.start();
        }

I hope this will solve your problem.

Thread Thread
 
msumanphexaware profile image
MsumanP-hexaware • Edited

Now error is not coming but window.AmbientLightSensor is coming as undefined.