简体   繁体   English

在两个组件中使用nativeElement

[英]Use nativeElement in two components

I am get this error when using autocomplete for angular maps(AGM), 使用自动完成角度图(AGM)时出现此错误,

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

, when using ElementRef for angular public searchElement: ElementRef; ,当使用ElementRef进行角度public searchElement: ElementRef; .

line am getting the error: 行出现错误:

  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;
        });
      });
    });
  }

In my view component 在我看来

  <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>

Am using this in two components, in one it works fines on the other it give thats error. 我在两个组件中使用它,在一个组件中它可以很好地工作,而在另一个组件中则提供多数民众赞成的错误。 Have tried to use different names for element ref but sting the same error. 尝试为元素ref使用不同的名称,但遇到相同的错误。

You should declare a variable like 你应该声明一个像

@ViewChild("search") public searchElementRef: ElementRef;

instead of 代替

public searchElement: ElementRef

which means searchElement variable is referring the search template reference mentioned inside your template as (#search) wrt input element. 这意味着searchElement变量searchElement模板中提到的search模板引用称为(#search) wrt input元素。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM