简体   繁体   English

错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ nativeElement”

[英]ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined

I am getting the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined. 我收到以下错误:错误错误:未捕获(承诺):TypeError:无法读取未定义的属性'nativeElement'。

This occurs when I try to add a div with an ngIf and inside a google map: 当我尝试在google map中添加带有ngIf的div时,会发生这种情况:

HTML: HTML:

                <div class="form-group">
                <label>Location by map?</label>
                <mat-select formControlName="ubication" [(ngModel)]="mapVisibility" class="form-control" placeholder="Select option">
                    <mat-option disabled>Select option</mat-option>
                    <mat-option value="visible">Yes</mat-option>
                    <mat-option value="hidden">No</mat-option>
                </mat-select>
            </div>

            <div *ngIf="mapVisibility === 'visible'">
                <div class="example-form">
                    <mat-form-field class="example-full-width">
                        <input matInput type="text" (keydown.enter)="$event.preventDefault()" autocorrect="off" autocapitalize="off" spellcheck="off" #agmSearch placeholder="Enter address">
                    </mat-form-field>
                </div>

                <agm-map id="googleMap" [latitude]="lat" [longitude]="lng" [zoom]="zoom">
                    <agm-marker [latitude]="lat" [longitude]="lng" [markerDraggable]="true" (dragEnd)="markerDragEnd($event)"></agm-marker>
                </agm-map>
            </div>

TS: TS:

mapVisibility: string;

ngOnInit() {
    this.getPlacesAutocomplete();
}

getPlacesAutocomplete() {
// load Places Autocomplete
this.mapsAPILoader.load().then(() => {
this.setCurrentLocation();
this.geoCoder = new google.maps.Geocoder;

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.lat = place.geometry.location.lat();
  this.lng = place.geometry.location.lng();
  this.zoom = 12;
  });
 });
});
}

private setCurrentLocation() {
if ('geolocation' in navigator) {
  navigator.geolocation.getCurrentPosition((position) => {
    this.lat = position.coords.latitude;
    this.lng = position.coords.longitude;
    this.zoom = 15;
    this.getAddress(this.lat, this.lng);
  });
}
}

  getAddress(latitude, longitude) {
this.geoCoder = new google.maps.Geocoder();
this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => {
  console.log(results);
  if (status === 'OK') {
    if (results[0]) {
      this.zoom = 12;
      this.address = results[0].address_components[1].long_name + ' ' + results[0].address_components[0].long_name;
    } else {
      window.alert('No results found');
    }
  } else {
    window.alert('Geocoder failed due to: ' + status);
  }
});
}

I extracted the code from here: Angular 8/7 | 我从这里提取了代码: Angular 8/7 | Add Google Maps with Location Search in Angular 2 plus Applications using Angular Google Maps Module (@agm/core) Easily 使用Angular Google Maps模块(@ agm / core)轻松在Angular 2加上应用程序中添加带有位置搜索的Google Maps

ERROR: Image error 错误: 图片错误

Although I get this error, the map works fine, but I cannot implement the search for places by entering an address in an input, which does work if I remove the div that contains the ngIf. 尽管出现此错误,但地图工作正常,但是我无法通过在输入中输入地址来实现对地点的搜索,如果我删除了包含ngIf的div,它就可以工作。 what is this about? 这是怎么回事 Any ideas? 有任何想法吗?

use ngAfterViewInit instead of ngOnInit 使用ngAfterViewInit而不是ngOnInit

ngAfterViewInit () {
    this.getPlacesAutocomplete();
}

View queries are set before the ngAfterViewInit callback is called. 视图查询是在调用ngAfterViewInit回调之前设置的。

you need the change the *ngIf to hidden this way the elemnt will be avilable otherwise the searchElementRef will be null until the condition is true 您需要将*ngIf更改为以这种方式hidden否则searchElementRef将可用,否则searchElementRef将为null直到条件为真

<div [hidden]="mapVisibility === 'visible'">
 ...
</div>

Call your function after the Component is initialized (DOM Loaded) on ngAfterViewInit ngAfterViewInit上初始化组件(加载DOM)后调用函数

ngAfterViewInit() {
    this.getPlacesAutocomplete();
}

Or surround your code on setTimeout (Bad idea) : 或者将代码放在setTimeout上(错误的主意):

ngOnInit() {

setTimeout( _ =>   this.getPlacesAutocomplete() , 1000)

}

if you are using ngAfterViewInit don't forget class MyComponent implements AfterViewInit 如果您使用的是ngAfterViewInit请不要忘记class MyComponent implements AfterViewInit

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误TypeError:无法读取未定义的属性“nativeElement” - ERROR TypeError: Cannot read property 'nativeElement' of undefined 错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“id” - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'id' of undefined 错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“ map” - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined 错误错误:未捕获(承诺):类型错误:无法读取未定义的属性“key” - ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'key' of undefined 错误:未捕获(承诺):TypeError:无法读取未定义的属性“ customerName” - Error: Uncaught (in promise): TypeError: Cannot read property 'customerName' of undefined “错误:未捕获(在承诺中):TypeError:无法读取未定义的属性”长度“ - “Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined” 错误:未捕获(承诺):TypeError:无法读取未定义的属性“ title” - Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined 错误:未捕获(承诺中):TypeError:无法读取未定义的属性“pushTag” - Error: Uncaught (in promise): TypeError: Cannot read property 'pushTag' of undefined Angular 5:ERROR TypeError:无法读取未定义的属性&#39;nativeElement&#39; - Angular 5 :ERROR TypeError: Cannot read property 'nativeElement' of undefined 错误TypeError:无法读取角度5中未定义的属性&#39;nativeElement&#39; - ERROR TypeError: Cannot read property 'nativeElement' of undefined in angular 5
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM