【问题标题】:Accessing a specific instance of a component (edited)访问组件的特定实例(已编辑)
【发布时间】: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


    【解决方案1】:

    这是对我的编辑的回答。

    关键是用“queryAll”代替“query”,然后把所有的DebugElements变成SnackTime的实例。这将产生一个包含所有 SnackTime 元素的数组,包括其他 html 文件中的元素。

        let debugComponentsInThePage:DebugElement[] = fixture.debugElement.queryAll(By.directive(SnackTime));
        let componentsInThePage:SnackTime[] = [];
    
        for(var i=0; i<debugComponentsInThePage.length; i++){
            componentsInThePage[i] = debugComponentsInThePage[i].componentInstance;
            console.log(componentsInThePage[i]);
        }
    

    【讨论】:

      【解决方案2】:

      您可以使用模板引用变量

      如果您想在 model.ts 文件中操作该组件实例,您可以使用 @ViewChild 装饰器(如 @ViewChild('cookies') cookies: SnackTimeComponent)来获取对它的引用。

      或者你可以在模板的其他地方使用它。 &lt;div&gt;I have {{cookies.numCookies}} cookies!&lt;/div&gt;

      (假设 SnackTimeComponent 类中存在 numCookies 属性)

      【讨论】:

      • 如果使用@ViewChildren(SnackTimeComponent) snaks:QueryList&lt;SnackTimeComponent&gt;,您将拥有所有的时间。 this.snaks.find(x=&gt;x.bestSnack=='Cookies') 给你送饼干。请参阅文档:angular.io/api/core/ViewChildren
      • 在规范文件中呢?我正在做单元测试,我似乎无法访问原始 .ts 文件之外的组件。
      • 我已经以不同的方式解决了这个问题,但感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      相关资源
      最近更新 更多