【发布时间】:2019-11-30 20:45:17
【问题描述】:
我正在尝试访问应用程序在其他组件中多次使用它的组件的特定实例。当我使用查询命令“fixture.debugElement.query(By.directive(ComponentName)).componentInstance;”时,它只会选择第一个创建的 ComponentName 实例。
我已将示例分解为这个基本版本:
random.test.component.html
<random-test-child>
</random-test-child>
<snack-time
[bestSnack]="cheeseAndCrackers">
</snack-time>
random.test.component.child.html
<snack-time
[bestSnack]="applesAndOranges">
</snack-time>
<snack-time
[bestSnack]="cookies">
</snack-time>
*所有变量名都是各自 .ts 文件中的字符串(例如,applesAndOranges 是“Apples and Oranges”)
查询命令选择的组件有“Apples and Oranges”作为 bestSnack 的值。如果我想专门访问“Cookies”或“Cheese and Crackers”,有没有办法做到这一点(除了添加一个 id 标签)?
编辑
好的,不同的计划:我在规范文件中使用 fixture.debugElement.query(By.directive(SnackTime)).componentInstance 来挑选 SnackTime 元素。我在原始的 random.test.component.html 中添加了另一个 SnackTime,所以它现在如下所示:
<snack-time
[bestSnack]="cheeseAndCrackers">
</snack-time>
<snack-time
[bestSnack]="chipsAndSoda">
</snack-time>
我的想法是创建一个 QueryList 或 SnackTime 元素数组,并从中挑选出特定的实例。但是,如果我这样做:
让 componentsInThePage:SnackTime[] = fixture.debugElement.query(By.directive(SnackTime)).componentInstance;
我得到一个数组,它只有第一个创建的 SnackTime 组件,而不是 random.test.component.html 文件中的两个(child.html 文件中的两个也不出现)。如何创建 SnackTime 组件的列表/数组?
【问题讨论】:
标签: angular typescript unit-testing karma-runner