@ViewChildren does not get updated with dynamically added DOM elements

折月煮酒 提交于 2019-12-07 05:02:31

问题


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?


回答1:


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.




回答2:


At point when you add new element in your carousalElement div at that time check in DOM if that element is available or not.

If available get element by:

this.carousalElements.NativeElement......

If not available then try to set some timeout then after check again in DOM

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

Still not find then try with below logic:

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

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

Let me know what it gives



来源:https://stackoverflow.com/questions/43510444/viewchildren-does-not-get-updated-with-dynamically-added-dom-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!