Sunday, October 22, 2017

Accessing Style of Ionic 2 DOM Elements

Leave a Comment

I'm trying to access the DOM elements of one of my pages with the following:

 ionViewDidEnter() {      this.platform.ready().then(() => {        let elm = <HTMLElement>document.querySelector("ion-navbar.toolbar.toolbar-ios.statusbar-padding");       console.log(elm.style);     })  } 

However, it appears this element has no style - I have tried various combinations to access it but no luck.

Specifically, I'm looking for the height of the ion-navbar. Is this possible?

3 Answers

Answers 1

You can get the actual height of an element with element.offsetHeight.

As for the style property, it will give you only the attributes defined in the element's inline style attribute (e.g. <div style="height: 20px;">...</div>), not the ones applied by the CSS using selector rules. See this MDN article for more details.

Answers 2

This is my workaround for that.

let tabs = document.querySelectorAll('.show-tabbar');       if (tabs !== null) {           Object.keys(tabs).map((key) => {               tabs[key].style.transform = 'translateY(56px)';           });   } 

Answers 3

I always have found it terribly useful to simply use ionic serve inspect the element in chrome and easily see the style for the given device.

To access the DOM element in angular I have used the #id route. The following snippet was used to verify the appropriate class was applied by ionic.

html- home.html

<ion-spinner #testspinner name="crescent" paused="{{isPaused}}"></ion-spinner> 

ts- home.ts

import {Component} from '@angular/core'; import {ViewChild} from '@angular/core';   @Component({   selector: 'page-home',   templateUrl: 'home.html' }) export class HomePage {   isPaused: boolean;   @ViewChild('testspinner') testspinner;    constructor() {     this.isPaused = false; // set to true will cause to never have animation state running.   }     containsPausedClass(list: string[]) {     return (list.indexOf('spinner-paused') != -1);   }    ngAfterViewInit() {     // if the spinner is allows to load without 'spinner-paused' then safari will work.     setTimeout(() => {       this.isPaused = true;     }, 0);     console.log('test spinner is paused ',       this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));    }    togglePause() {     this.isPaused = !this.isPaused;      setTimeout(() => {        console.log('test spinner is paused ',         this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));     }, 100);   }  } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment