angular - 在两个组件中使用 nativeElement
问题描述
使用角度地图(AGM)的自动完成时出现此错误,
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
, 当ElementRef
用于 angular时public searchElement: ElementRef;
。
行出现错误:
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
@ViewChild("search")
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone
) {}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
this.zoom = 12;
});
});
});
}
在我看来组件
<div class="form-group">
<input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
</div>
<agm-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<agm-marker [latitude]="latitude" [longitude]="longitude"></agm-marker>
</agm-map>
我在两个组件中使用它,一个它工作正常,另一个它给出了错误。已尝试对元素引用使用不同的名称,但会出现相同的错误。
解决方案
您应该声明一个变量,例如
@ViewChild("search") public searchElementRef: ElementRef;
代替
public searchElement: ElementRef
这意味着searchElement
变量将search
模板中提到的模板引用称为(#search)
wrtinput
元素。
推荐阅读
- python - 如何在 QTextEdit 中进行计算时实时更新文本,而不会冻结界面?
- kubernetes - 在部署 Kubernetes 部署配置文件时为 AWS Fargate 设置 `platformVersion`
- inversion-of-control - 使用 Simple Injector 注册类型时的回调操作
- javascript - 倒数计时器自动触发提交按钮
- c# - 扩展方法中的访问依赖
- swift - UIImagePicker 不显示使用编辑器选择的图像部分
- sql - 查询以查找最后 N 个事件类型“2”紧接在事件类型“1”之前发生
- angular - 在 Angular 模板表单中获取自定义验证时出现问题
- css - CSS:在浏览器调整大小时保持一致的段落高度
- xml - PowerShell 获取所有相关值