【发布时间】:2018-08-06 12:18:12
【问题描述】:
我在我的一个组件 (favorite-places) 中引用了 @ViewChild,这是 Google 地图自动完成功能的搜索输入字段。
一切正常,除非我导航到另一个位置并返回favorite-places。
这是组件的布局。请注意,有一个 [couterLink]="['../select']" 可以让我导航到另一个位置。
<div *headerContent fxFlex fxLayout="row" fxLayoutAlign="space-between center"
style="padding-left: 5px; padding-right: 5px;">
<div fxLayoutAlign="center center" style="">
<mat-icon>search</mat-icon>
<mat-form-field class="form-group">
<input #search matInput placeholder="Search" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" [formControl]="searchControl">
</mat-form-field>
</div>
<button mat-icon-button [routerLink]="['../select']" [queryParams]="{groupId: groupId}" (click)="addPlace()">
<mat-icon>check</mat-icon>
</button>
</div>
<div>
<div class="container">
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom" style="height:150px; margin-top: 15px;">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
</div>
<div>
<span>PlaceID: {{selectedPlace?.place_id}}</span><br/>
<span>Name: {{selectedPlace?.name}}</span>
</div>
</div>
正如我所说,一切正常,除了当我进入这个地方,离开它然后返回它。在这种情况下,我会看到这个错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
at favorite-places.component.ts:61
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:4062)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
...
这是发生错误的地方:
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(
this.searchElementRef.nativeElement,
{ types: ['establishment'] });
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
// ..
});
});
}
);
export class FavoritePlacesComponent implements OnInit {
// ..
@ViewChild("search")
public searchElementRef: ElementRef;
}
似乎this.searchElementRef 在离开该位置后被取消或未定义。然而,回到它并不会重新创建它。这对我来说似乎是一个生命周期问题,但我不知道如何解决。
【问题讨论】:
-
你是在访问 ngAfterViewInit() 中的 nativeElement 吗?
-
@SureshKumarAriya 不。我现在没有实现这个功能。
-
只有在屏幕上渲染 DOM 时才能访问 viewchild 元素属性。所以请在 ngAfterViewInit() 方法中添加。
标签: angular