-1

In Angular, if I want to add a DOM element called elem1 dynamically and want to run some method to make elem1 for example draggable, how can I determine that the DOM element is ready for use? Because if I run the draggable method instantly after the DOM element adding function, it may doesn't work some times.

I tried OnChanges in ng but it seems this only works for @Input rather than DOM.

So I am now using jQuery.ready() function but I wonder if there is more elegant way in Angular.

Zanecola
  • 1,394
  • 3
  • 15
  • 27

2 Answers2

0

You must use @ViewChild decorator and access the element inside ngAfterViewInit() lifecycle hook.

Like this:

ts file

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  @ViewChild('myEl') el: ElementRef;

  ngAfterViewInit() {
    // element is ready for use
    console.log(this.el.nativeElement);
  }
}

html file

<div #myEl></div>
Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
0

You can try to use ngOnInit or ngAfterViewInit from this answer Angular2 equivalent of $document.ready()

But imagine a situation where your components are added dynamically during working with the page. I assume that your makeDraggable function is making some element <div data-draggable="true"></div> "draggable" but the problem is that you try to do it once.

Maybe you need to use event delegation and listen to click event on body, look at event.target.dataset.draggable property and if it's true - apply your makeDraggable function here. This is a very common way to handle components creation time of which you're not aware about.

davidluckystar
  • 928
  • 5
  • 15