@ViewChildren is not 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 all divs with a class carousalElements

usingViewChildren

@ViewChildren('carousalElement') carousalElements;

      

PROBLEM: When I dynamically add a new one div

to the div #carousalElement

it doesn't show up in the array carousalElements

.

Am I missing something obvious?

+3


source to share


2 answers


Angular does not recognize HTML not added by Angular directives or APIs. Also, if it <div>

doesn't have a template variable #carousalElement

, @ViewChildren('carousalElement')

it won't find it.



Template variables must be added statically to the component template. Adding them dynamically is pointless. Angular only handles the construction of Angular templates when compiling the template.

+4


source


The moment you add a new element to your carousalElement

div at this time, check the DOM if this element is available or not.

If available, get the item:

this.carousalElements.NativeElement......

      

If not available try setting some timeout and then check again in DOM

setTimeout(() => {
        //your logic
    }, 200);

      



Still not found, then try with below logic:

@ViewChildren('carousalElement', { read: ViewContainerRef })
public carousalElement: QueryList<ViewContainerRef>;

      

And where do you check console.log (this.carousalElement)

Let me know what he gives

-1


source







All Articles