如何在@angular/google-maps信息窗口中使用Angular Material数据网格
解决Angular 17中Google Maps信息窗口集成Angular Material网格的问题
你当前的实现无法渲染出Material网格,核心原因是通过[innerHTML]插入的Angular组件字符串不会被Angular编译。Material组件(如mat-grid-list)需要Angular的编译流程才能初始化样式和功能,直接插入HTML字符串只会生成普通DOM元素,无法触发组件逻辑。
修改方案
直接在map-info-window标签内编写Material网格的模板,通过绑定数据来动态展示内容,而非拼接HTML字符串。
1. 更新组件逻辑(app.component.ts)
添加变量存储当前点击标记的对应数据,移除拼接HTML的逻辑:
import { Component, ViewChild } from '@angular/core'; import { CommonModule } from '@angular/common'; import { GoogleMapsModule, MapInfoWindow, MapMarker, } from '@angular/google-maps'; import { MapService } from './services/map.service'; import { MatGridListModule, MatGridTileModule } from '@angular/material/grid-list'; @Component({ selector: 'app-root', standalone: true, imports: [ CommonModule, RouterOutlet, GoogleMapsModule, MatToolbarModule, FilterComponent, MatGridListModule, MatGridTileModule // 必须导入该模块才能使用mat-grid-tile ], templateUrl: './app.component.html', styleUrls: ['./app.component.less'], }) export class AppComponent { @ViewChild(MapInfoWindow, { static: false }) infoWindow!: MapInfoWindow; mapsData: any; markers: any[] = []; currentMarkerData: any; // 存储当前标记的展示数据 constructor(private mapService: MapService) {} openInfo(marker: MapMarker, markerData: any) { this.currentMarkerData = markerData; // 传入当前标记的自定义数据 this.infoWindow.open(marker); } }
2. 修改模板(app.component.html)
直接在map-info-window内编写Material网格模板,绑定currentMarkerData:
<google-map height="500px" width="900px" [center]="center" [zoom]="zoom" (mapClick)="moveMap($event)" (mapMousemove)="move($event)" > <map-marker #markerElem="mapMarker" *ngFor="let marker of markers" [position]="marker.position" [label]="marker.label" [title]="marker.title" [options]="marker.options" (mapClick)="openInfo(markerElem, marker.data)" > <map-info-window> <!-- 直接使用Material网格组件,绑定数据 --> <mat-grid-list cols="2" rowHeight="2:1"> <mat-grid-tile>{{ currentMarkerData?.tile1 }}</mat-grid-tile> <mat-grid-tile>{{ currentMarkerData?.tile2 }}</mat-grid-tile> <!-- 可根据实际需求添加更多网格项 --> </mat-grid-list> </map-info-window> </map-marker> </google-map>
3. 准备标记数据
确保你的markers数组中每个标记都包含展示所需的data属性,例如:
// 示例标记数据 this.markers = [ { position: { lat: 40.7128, lng: -74.0060 }, label: 'NY', title: 'New York', data: { tile1: '纽约人口:833万', tile2: '时区:UTC-5' } }, { position: { lat: 34.0522, lng: -118.2437 }, label: 'LA', title: 'Los Angeles', data: { tile1: 'LA人口:389万', tile2: '时区:UTC-8' } } ];
说明
这种方式下,Angular会正常编译mat-grid-list和mat-grid-tile组件,Material的样式和功能都能正常生效,因为模板属于Angular组件的一部分,而非动态插入的未编译字符串。
内容的提问来源于stack exchange,提问作者Rutuja Khandpekar
相关产品推荐
相关产品推荐

