Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ViewChildren does not get updated with dynamically added DOM elements

I have the following DOM structure

<div #carousalElement>
    <div  class="singleCaousalElement">
        <a>
            <img [src]="carousalURL1" class="carousalImage">
        </a>
    </div>
    <div  class="singleCaousalElement">
        <a>
            <img [src]="carousalURL2" class="carousalImage">
        </a>
    </div>
</div>

I can get the all divs with carousalElements class using the ViewChildren

@ViewChildren('carousalElement') carousalElements;

PROBLEM: When I dynamically add a new div under the #carousalElement div, it does not show up under the carousalElements array.

Am I missing something obvious?

like image 754
Giridhar Karnik Avatar asked Apr 20 '17 04:04

Giridhar Karnik


2 Answers

Angular doesn't recognize HTML not added by Angular directives or APIs. Also if the <div> doesn't have a template variable #carousalElement, @ViewChildren('carousalElement') won't find it.

Template variables need to be added statically in the components template. Adding them dynamically is meaningless. Angular processes Angular-specific template constructs only during compilation of a template.

like image 55
Günter Zöchbauer Avatar answered Oct 30 '22 21:10

Günter Zöchbauer


You can add the service ChangeDetectorRef and call the method this.changeDetectorRef.detectChanges() when you add another child with the ref that you have referenced in ViewChildren QueryList. That worked for me!

like image 42
Gerard Avatar answered Oct 30 '22 22:10

Gerard