0

I'm modifying a component (specifically a custom-rendered drop down list) to allow one to pass in a variable in the HTML and pre-select an item from the drop down.

ngAfterViewInit() seemed like the right place to grab the variable, and then update the view based on it.

I could not get it to work. It did everything except actually update the DOM to reflect the change.

I finally decided that maybe I should just brute-force it and instead of passing variables to functions within the angular I'll just grab the DOM object and click it:

...click()

Again, all the logic would fire, but the state in the DOM wouldn't actually update to reflect that.

I finally tried the "wrap it in a setTimeout" hack:

setTimeout(function(){
    ...click()
},100);

And...that worked!

Why?

Am I using the wrong hook? Or misunderstanding ngAfterViewInit()?

I noticed that I could put my call in ngAfterViewChecked() and it would work just fine there...but the problem, of course, is that hook is being constantly called, so my UI would get stuck in a loop if I place it there.

Is my having to use setTimeout a sign of something wrong elsewhere? (I assume it is, but not sure what that something wrong would be...)

DA.
  • 39,848
  • 49
  • 150
  • 213
  • is that specific element wrapped in an *ngIf at any given time? – David Anthony Acosta Jul 26 '18 at 16:08
  • In my click() example, yes, the actual element being 'clicked' is being rendered frominside an ngFor loop (looping through data to create each item of the drop down) – DA. Jul 26 '18 at 16:17
  • @DavidAnthonyAcosta oops. Forgot to @ you ^ – DA. Jul 26 '18 at 16:23
  • Can we see the markup? And the relevant parts of the code? – ConnorsFan Jul 26 '18 at 16:32
  • I can only suspect since there isn't any code. But it sounds like your hook isn't working due to a directive stopping it. You may be able to work around this by leaning on an Observable to handle the click event, the timeout you have can be applied with `.throttle()` – Callat Jul 26 '18 at 16:34
  • Possible duplicate of [Retrieve elements created by ngFor in ngAfterViewInit](https://stackoverflow.com/questions/49226233/retrieve-elements-created-by-ngfor-in-ngafterviewinit) – ConnorsFan Jul 26 '18 at 16:35
  • @ConnorsFan let me try. This is a complex mess at the moment (not my coding). – DA. Jul 26 '18 at 16:38
  • @Callat thanks. I'll look into that. – DA. Jul 26 '18 at 16:38

0 Answers0