简体   繁体   中英

how to get the size of an ion-col in angular 8

I'm trying to get the ion-col size in angular 8

My code works very well if I want the size of a <div> but doesn't work if I want from <ion-col> .

I get this error message:

ERROR TypeError: Cannot read property 'offsetWidth' of undefined

Someone have an idea if it's possible to do it and how to do ?

Thanks you very much for help

CSS Code:

div {
    margin: auto;
    height: 50px;
    border: 1px solid black;
}

TS Code:

  @ViewChild('container', { static: true }) container: ElementRef;

  getInfo() {
    const width = this.container.nativeElement.offsetWidth;
    const height = this.container.nativeElement.offsetHeight;
    console.log('width : ', width, ' + ', height);
  }

HTML Code:

<ion-content>

  <ion-grid>
    <ion-row>

      <ion-col size="6" (click)="getInfo()" #container>
        <div></div>
      </ion-col>

    </ion-row>
  </ion-grid>

</ion-content>

That's because <ion-col> is not a ElementRef

You should have something like :

@ViewChild('container', {read: ElementRef}) container: ElementRef;

And then :

this.container.nativeElement.offsetHeight

this work for me in ionic 5

TS CODE

@ViewChild('container', {read: ElementRef}) container: ElementRef;



  getInfo() {
    const width = this.container.el.offsetWidth; // instead of this.container.nativeElement.offsetWidth;
    const height = this.container.el.offsetHeight;
    console.log('width : ', width, ' + ', height);
  }

HTML CODE


    <ion-row>
      <ion-col size="12" #container>
        .....
      </ion-col>
    </ion-row>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM