0

I have an element that that is conditionally inserted with an *ngIf condition. When it is inserted I want to scroll it into view. The following technique works but it seems clumsy and I would like to improve it.

          <app-text-create id="textcreate" *ngIf="modeNewEntry"          
                  (load)="document.getElementById('textcreate').scrollIntoView()"
          ></app-text-create>

When the component state property modeNewEntry goes true the text entry box gets inserted on the bottom of the page. Without the scrollIntoView() call it is generally not visible.

Is there a better way to get access to the HTMLElement than the document.getElementById(..) expression?

PS. The IDE I am using, WebStorm, thinks the document reference as undefined even though this does works. Is that a bug or is there a reason for that?

1
  • Do you had try using reference ? Commented Dec 28, 2019 at 6:00

1 Answer 1

1

Add the component in a wrapping div:

<div #textCreate>
  <app-text-create id="textcreate" *ngIf="modeNewEntry">
  </app-text-create>
</div>

And then when you click a button to set modeNewEntry to true, also call scrollIntoView() on the ElementRef's nativeElement for this div:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  modeNewEntry = false;
  @ViewChild('textCreate', { static: false }) textCreateComponent: ElementRef;

  showComponent() {
    this.modeNewEntry = true;
    this.textCreateComponent.nativeElement.scrollIntoView();
  }
}

Here's a Working Code Demo 🚀 for your ref.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought about using the ViewChild decorator but I forgot that about the nativeElement property that it is contained. Also I don't need the id attribute anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.