4

I'm struggling with putting a map on a second segment. It's a typical problem, and I've found several solutions, but they don't work for me because the events seem to get fired before the segment is build completely. I don't know if this is because of a breaking change in Ionic, or because I am doing it wrong.

page.html:

<ion-toolbar>
  <ion-segment [(ngModel)]="view" (ionChange)="changeSegment()">
    <ion-segment-button value="list">
      <ion-icon name="list-box" isActive="false"></ion-icon>
    </ion-segment-button>
    <ion-segment-button value="map" (ionSelect)="selectMap()">
      <ion-icon name="map" isActive="false"></ion-icon>
    </ion-segment-button>
  </ion-segment>
</ion-toolbar>

<ion-content [ngSwitch]="view">
  <div *ngSwitchCase="'list'"></div>
  <div *ngSwitchCase="'map'">
    <div id='map'>Here the map comes.</div>
  </div>
</ion-content>

page.js:

import {Component} from "@angular/core";

@Component({
  templateUrl: 'build/pages/page/page.html'
})
export class Timeline {
  constructor() {
    this.view = "list";
    this.selectMap = function() {
      console.log("selectMap:", document.getElementById("map"));
    }
    this.changeSegment = function() {
      console.log("changeSegment:", document.getElementById("map"));
    }
  }
}

(Yeah, that project is using JavaScript, not TypeScript.)

With both the change and the select events, on first click they return "null" for the map element, and only on a second click they return the correct element.

To me it looks like the events are fired before the segment is complete. (But I may just as well be making a stupid beginners mistake...)

How do I know when the #map element is available?

Peter
  • 2,874
  • 2
  • 31
  • 42
  • Instead of trying to obtain the element with the ID (like you'd do it in JQuery), why don't you create a custom directive? That way, the map would be initializated when the element is included in the DOM (because the ngSwitch adds and removes the element) and you won't need to worry about it. [This SO answer](http://stackoverflow.com/questions/26579678/when-has-ng-switch-finished-rendering) may help you too (although it's ng1, the concept is the same). – sebaferreras Aug 14 '16 at 09:40
  • 1
    Thanks @sebaferreras, I will look into that! – Peter Aug 15 '16 at 11:41

0 Answers0