@ViewChildren没有使用动态添加的DOM元素进行更新

Gri*_*mer 5 viewchild angular

我有以下DOM结构

<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>
Run Code Online (Sandbox Code Playgroud)

我可以用carousalElements类来获得所有divViewChildren

@ViewChildren('carousalElement') carousalElements;
Run Code Online (Sandbox Code Playgroud)

问题:当我div#carousalElementdiv 下动态添加一个新的时,它不会显示在carousalElements数组下面.

我错过了一些明显的东西吗

Gün*_*uer 6

Angular不识别Angular指令或API未添加的HTML.此外,如果<div>没有模板变量#carousalElement,@ViewChildren('carousalElement')将无法找到它.

需要在组件模板中静态添加模板变量.动态添加它们毫无意义.Angular进程仅在编译模板期间构造Angular特定的模板.


San*_*per 0

当您在carousalElementdiv 中添加新元素时,请检查 DOM 该元素是否可用。

如果可用,通过以下方式获取元素:

this.carousalElements.NativeElement......
Run Code Online (Sandbox Code Playgroud)

如果不可用,则尝试设置一些超时,然后在 DOM 中再次检查后

setTimeout(() => {
        //your logic
    }, 200);
Run Code Online (Sandbox Code Playgroud)

仍然没有找到然后尝试以下逻辑:

@ViewChildren('carousalElement', { read: ViewContainerRef })
public carousalElement: QueryList<ViewContainerRef>;
Run Code Online (Sandbox Code Playgroud)

以及在哪里检查 console.log(this.carousalElement)

让我知道它能带来什么