gpt4 book ai didi

javascript - 如何在Angular2中调用Polymer元素方法?

转载 作者:行者123 更新时间:2023-12-01 05:36:03 27 4
gpt4 key购买 nike

我正在使用 Angular2 和 Polymer(我知道 Angular 目前是 alpha)。

主要目标:

构建一个小型应用程序,使用 Angular2 和 Polymer 显示我在 Gmap 中的当前位置。

当前 BabyStep

使用 setInterval 在 ViewModel/Component 中移动坐标。

问题

我尝试使用 Gmap element from Polymer在 Angular View 内。绑定(bind)工作完美,但 map 不刷新。我读到,我必须从 google-map element API 调用 refresh() 方法。这使我得出以下结论:

@Component({
selector: 'my-app',
})
@View({
templateUrl: '/templates/map.html'
})
export class MapComponent {
lat: number;
lng: number;

constructor() {
this.lat = 27.859862;
this.lng = 13.112473;
this.goToleft();
}

goToleft() {
setInterval(() => {
this.lng -= 0.00001;
document.querySelector("#gmap").resize();
}, 100)
}
}

map .html:

<link rel="import" href="../bower_components/google-map/google-map.html" >
<link rel="import" href="../bower_components/google-map/google-map-marker.html" >
[...]
<google-map id="gmap" show-center-marker libraries="places" latitude="{{lat}}" longitude="{{lng}}" disable-zoom fit-to-markers disable-default-ui zoom="18" >
<google-map-marker longitude="{{lng}}" latitude="{{lat}}" id="google_map_marker" title="Go Giants!" draggable="true"> </google-map-marker>
</google-map>

说实话:document.querySelector("#gmap").resize();很脏。根据我的理解,Angular2 中的组件就像 ViewModel 一样工作,有点像 Angular1 中的 Controller 。因此 ViewModel 不应该直接访问 DOM 元素。但我还没有更好的解决方案。

我尝试使用的ElementRef injection ,但不再支持。

有人能给我提示吗?我感觉我错过了什么。

最佳答案

我正在使用 Angular2 alpha 46 并具有以下构造函数,该构造函数将 ElementRef 注入(inject)到组件中。我同意你的观点,这似乎不是最好的解决方案,但我还没有看到任何其他方法。

constructor( 
@Inject(ElementRef) elementRef: ElementRef
) {
this.map = elementRef.nativeElement.querySelector("XXX");
this.refreshMap = this.map.refresh;
}

关于javascript - 如何在Angular2中调用Polymer元素方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com