Herberts Markūns Herberts Markūns - 10 days ago 5
Javascript Question

How to get an element with condition of modal dialog in Angular 2?

I'm using ng2-modal to create a modal dialog in Angular 2. I am unable to get an element that has a condition on it (#myModalScrollPanel).

Template (modal.html):

<modal #myModal title="{{title}}"
cancelButtonLabel="Close"
submitButtonLabel="Ok"
modalClass="@modal-md"
[hideCloseButton]="false"
[closeOnEscape]="false"
[closeOnOutsideClick]="false"
>
<modal-header></modal-header>
<modal-content>
<div class="row">
<div *ngIf="logOutput" class="col-md-12">
<div id="myModalScrollPanel" #myModalScrollPanel class="panel-body fixed-panel">
<p *ngFor="let entry of logOutput.entries">{{entry.log}}</p>
</div>
</div>
</div>
</modal-content>
<modal-footer></modal-footer>
</modal>


In my component I get View Children (modal.component.ts):

@ViewChild('myModal') myModalModal;
@ViewChild('myModalScrollPanel') myModalScrollPanel;


After a users clicks a button, I show the modal and get log text from the server, I call updateScrollPosition() once I have updated logOutput (modal.component.ts):

updateScrollPosition() {
console.log("modal:");
console.log(this.myModalModal);
console.log("log scroll panel:");
console.log(this.myModalScrollPanel);

if(this.myModalScrollPanel){
console.log("Scrolling the panel down");
this.myModalScrollPanel.nativeElement.scrollTop = this.myModalScrollPanel.nativeElement.scrollHeight;
} else {
console.log("No log scroll panel.");
}
}


The console shows a valid object for "modal" and 'undefined' for log scroll panel.
I also tried calling that method from ngAfterViewInit(), but it only gets called when the parent component is loaded, and not the actual modal being shown, so the if statement results in false and element doesn't exist yet. If I remove/move the if statement, so that the element exists I can then access that object, but the changes I make do not take any effect, although that might be a whole different issue (most likely to do with change detection).

In the end, I just want to scroll to the bottom of the panel. Something like this (which works in the browser console):

var scrollPanel = document.getElementById('myModalScrollPanel');
scrollPanel.scrollTop = scrollPanel.scrollHeight;


Thanks in advance!

Answer

So to answer my own question, I had to use @ViewChildren instead of @ViewChild. @ViewChildren annotation will assign a QueryList object to your variable, giving you access to the elements you require (I use .toArray() to get an array of elements, which in this case will be just one).

Comments