I basically have a App which renders a small map. On this page is also a "toggle" button which hides the small map with a *ngIf in the parent component and displays the map in large instead. If I now import BrowserAnimationsModule in app.module.ts the large map is not rendered if I click on the toggle button (only if i set a timeout of 1ms before the map is created in ngOnInit of map-base.component.ts).
Sorry..it's a bit hard to explain, here's the code:
App.module.ts
...
@NgModule({
declarations: [
AppComponent,
MapSmallComponent,
MapLargeComponent,
MapBaseComponent
],
imports: [
BrowserModule,
FormsModule,
BrowserAnimationsModule, // comment this line, to make the app work
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
@Component({
selector: 'app-root',
template: `
<app-map-small *ngIf="small"></app-map-small>
<app-map-large *ngIf="!small"></app-map-large>
<button (click)="small = !small">Toggle</button>`,
styleUrls: ['./app.component.scss']
})
export class AppComponent {
small = true;
}
map-base.component.ts
@Component({
selector: 'app-map-base',
template: `<div id="map" class="map"></div>`,
styleUrls: ['./map-base.component.scss']
})
export class MapBaseComponent implements OnInit {
map: OlMap;
constructor() { }
ngOnInit() {
this.map = new OlMap({
target: 'map',
layers: [new OlTileLayer({ source: new OlOSM() })],
view: new OlView({ zoom: 13, center: fromLonLat([13.376935, 52.516181]) }),
controls: []
});
}
}
map-small.component.ts
@Component({
selector: 'app-map-small',
template: `
<p>other stuff</p>
<div style="max-width:500px">
<app-map-base></app-map-base>
</div>
<p>other stuff2</p>
`,
styleUrls: ['./map-small.component.scss']
})
export class MapSmallComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
map-large.component.ts
@Component({
selector: 'app-map-large',
template: `
<p>Some other stuff</p>
<app-map-base></app-map-base>`,
styleUrls: ['./map-large.component.scss']
})
export class MapLargeComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
dependencies
"dependencies": {
"@angular/animations": "^6.0.9",
"@angular/cdk": "^6.4.0",
"@angular/common": "^6.0.2",
"@angular/compiler": "^6.0.2",
"@angular/core": "^6.0.2",
"@angular/forms": "^6.0.2",
"@angular/http": "^6.0.2",
"@angular/material": "^6.4.0",
"@angular/platform-browser": "^6.0.2",
"@angular/platform-browser-dynamic": "^6.0.2",
"@angular/router": "^6.0.2",
"core-js": "^2.5.4",
"ol": "^5.1.3",
"rxjs": "^6.0.0",
"zone.js": "^0.8.26"
},
So why works everything fine, if I don't import BrowserAnimationsModule and it breaks if I import it? I want to use Angular Material, that's I would need it...
You have to use
ngAfterViewInit
, then you can be 'sure' the element inside your components template is present in the DOM.Here is a solution,
Component template
Component class implements
OnInit
and has the next propertyfinally initialize the map on
ngOnInit
method, you can useHope it helps.