我有以下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>
我可以使用carousalElements
ViewChildren
课程的所有div
@ViewChildren('carousalElement') carousalElements;
问题:当我在div
div下动态添加新的#carousalElement
时,它不会显示在carousalElements
数组下。
我错过了一些明显的东西吗?
答案 0 :(得分:6)
Angular不识别Angular指令或API未添加的HTML。此外,如果<div>
没有模板变量#carousalElement
,@ViewChildren('carousalElement')
将无法找到它。
模板变量需要在组件模板中静态添加。动态添加它们毫无意义。 Angular进程仅在编译模板期间构造Angular特定的模板。
答案 1 :(得分:0)
当你在carousalElement
div中添加新元素时,如果该元素可用,请检查DOM。
如果可用,则获取元素:
this.carousalElements.NativeElement......
如果不可用,则尝试设置一些超时,然后再次检查DOM
setTimeout(() => {
//your logic
}, 200);
仍然没有找到然后尝试以下逻辑:
@ViewChildren('carousalElement', { read: ViewContainerRef })
public carousalElement: QueryList<ViewContainerRef>;
检查console.log(this.carousalElement)
的位置让我知道它给出了什么
答案 2 :(得分:0)
JavaScript中有两种数据类型:基本数据和对象。
在Angular中,基本上有3种数据类型(这里有很多数据):基本数据,对象数据和反应数据。无需赘述
@ViewChildren('carousalElement') carousalElements;
是反应性数据类型。在Angular中,这意味着存在一个观察者,在这种情况下,模板数量为caoursalElement
的元素数量,您的变量carousalElements
是对@ViewChildren
的高级订阅形式,它是()=>{return this.carousalElements}
的观察者访问您只需要的更新数组
{{1}}
确保您的HTML模板正确使用了模板变量,并且此方法应该可以工作
答案 3 :(得分:0)
当您使用您在 ViewChildren QueryList 中引用的 ref 添加另一个孩子时,您可以添加服务 ChangeDetectorRef 并调用方法 this.changeDetectorRef.detectChanges()。这对我有用!