BobC
BobC

Reputation: 349

Angular 5 - How to getElementById from element inside *ngIf div?

I want to add an overlay that slides into view on my page. To do it, I am setting the style.width of the div during overlay open and close. The problem is the div is controlled by a *ngIf, and is undefined when my .ts code sets the *ngIf true and tries to set the div's width.

How can I get this working?

Component HTML:

    <div  *ngIf="showOverlay === true">
       <div id="myOverlay" class="overlay" style="margin-top: 25px;">
         <a href="javascript:void(0)" class="closebtn" (click)="closeOverlay()">&times;</a>
         <div class="overlay-content">
           <a href="#">Overlay is working!</a>
         </div>
       </div>
    </div>

    <div *ngIf="showOverlay === false" id="content" style="padding: 30px;">
    ...
    </div>

Component TS:

    public showOverlayFcn() {
      this.showOverlay = true;
      this.openOverlay();
    }  

    public openOverlay() {
      document.getElementById("myOverlay").style.width = "100%";
    }

    public closeOverlay() {
      document.getElementById("myOverlay").style.width = "0%";
    }

Thanks! Bob

Upvotes: 3

Views: 2171

Answers (3)

Richard Lovell
Richard Lovell

Reputation: 888

You could try using a conditional ngStyle attribute on the div with ID of myOverlay:

[ngStyle]="{'width': showOverlay ? '100%' : '0%'}"

Upvotes: 2

Rise
Rise

Reputation: 1601

Try to use setTimeout function as there maybe delay to enable element by ngIf.

public openOverlay() {
  setTimeout(function() {
     document.getElementById("myOverlay").style.width = "100%";
  }, 100);
}

Upvotes: 1

Khairul Islam
Khairul Islam

Reputation: 1215

Looks like you're not following the angular way. To get any element angular recommends to use @ViewChild. SO the proper way would be something like below:

<div *ngIf="showOverlay === true">
   <div #myOverlay class="overlay" style="margin-top: 25px;">
     <a href="javascript:void(0)" class="closebtn" (click)="closeOverlay()">&times;</a>
     <div class="overlay-content">
       <a href="#">Overlay is working!</a>
     </div>
   </div>
</div>

<div *ngIf="showOverlay === false" id="content" style="padding: 30px;">
...
</div>

And on your class file access it like this:

@ViewChild('myOverlay', { static: false }) myOverlay: ElementRef;

Even after this if you're not able to get the element then trigger a change detection like: this.changeDetectorRef.detectChanges();. Please remember to inject the ChangeDetectorRef in your constructor.

Upvotes: 2

Related Questions