0

I set element reference to my input,

export class MyComponent implements OnInit{

    @ViewChild("mySearchElement") // <input #mySearchElement 
    public searchElementRef: ElementRef;

...and bind it with google maps autosearch, which works fine.

new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, ...

What I try to do is, I want to render whole template after ajax call is completed. So I added a property to my component,

public isDataLoaded = false

and I set this true only after ajax work is completed.

<div *ngIf="isDataLoaded">
    ....my search element is within this wrapper.

...but when I do this, autocomplete cannot find searchElementRef, which is understandable.

How can I set viewchild after my ajax call is completed? This doesn't work:

function ajaxCallCompleted() { // Callback once ajax is completed.
    this.isDataLoaded = true
    @ViewChild("mySearchElement") this.searchElementRef: ElementRef;
    new google.maps.places.Autocomplete(this.searchElementRef.nativeElement ....
} 
tolga
  • 2,462
  • 4
  • 31
  • 57
  • Use `[style.display]="isDataLoaded ? 'block' : 'none'"` instead of `*ngIf` –  Mar 13 '19 at 08:22
  • I need to use *ngIf, style doesn't work in my flow for different reasons. – tolga Mar 13 '19 at 08:29
  • well you can't, so you'll have to find another way. it's either the style or `document.querySelector`, and I don't advise the latter one. –  Mar 13 '19 at 08:31
  • Try initializing the element with `@ViewChildren()`. Similar question to [Angular 2 @ViewChild annotation returns undefined](https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined) – Aakash More Mar 13 '19 at 09:24

2 Answers2

1

This happens because it cannot find the element reference. Use the hidden property instead:

<div [hidden]="!isDataLoaded">
  ...
</div>
Omar
  • 16,329
  • 10
  • 48
  • 66
  • I said it worked...but caused other problems about my flow. I need to find a way with *ngIf. – tolga Mar 13 '19 at 08:45
0

I found a solution. I carried search input to a different component and now all works fine.

<div *ngIf="isDataLoaded">
   <app-location-search location="data.location">...

Now on my sub component I can bind with google maps autocomplete like this:

export class LocationSearchComponent{

    @Input() location: any;

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

    constructor(public mapsAPILoader: MapsAPILoader) {

    }

    ngOnInit() {

    this.mapsAPILoader.load().then(() => {
        ...
tolga
  • 2,462
  • 4
  • 31
  • 57