Angular2,如何在代码中使用ng.probe来获取组件实例

时间:2017-04-05 11:40:38

标签: angular angular2-template

我知道我们可以使用ng.probe(element)在开发模式下在控制台中获取调试元素。

我知道如果你在单元测试中做query,你可以获得一个与ng.probe完全相同的调试元素。

有什么方法可以在代码中使用它吗?

我知道ng.probe中没有production mode,但有没有办法获取元素的组件实例?

我们能做到:

    getComponentInstance(element){

       ng.probe(element) // pseudo code
   }

基本上,我想看一些我没有动态创建的组件中的一些属性,所以我没有对它们的实例的引用,我不能仅仅因为ViewChild或类似的它们在我当前组件的视图或内容中。

我知道我可以通过创建一些服务并注入它来实现这一点,但我无法访问该组件以向其注入服务。

如果没有任何方法,他们ng.probe如何工作,为什么他们不提供此功能?

提前干杯。

2 个答案:

答案 0 :(得分:0)

如果您有权访问父组件构造函数,则可以注入:

ElementRef

constructor(private elm: ElementRef) { }

然后,您应该能够查询子组件内部html,以获得从单元测试query()获得的相同访问权限。

例如,我有一个父组件,它调用我公司为我们创建的组件的内部库:

 <dt-panel class="panel-bottom">
    <dt-panel-header class="transaction-history-panel-header">
        <dt-panel-title><i class="zmdi zmdi-share"></i> Transaction History</dt-panel-title>
        <dt-panel-actions class="amount-due-summary">
            <span>Total Amount Due <span class="amount-due">{{calculateTotalAmountDueDisplayValue() | currency: 'USD':true}}</span></span>
            <em>(Days Past Due: {{account?.daysPastDue}})</em>
        </dt-panel-actions>
    </dt-panel-header>
    <dt-panel-content>
        <dt-tabs class="transaction-history">
            <dt-tab-content tabTitle="Receipts" class="recent-payments">
                <recent-payments *ngIf="!loading" [receipts]="receipts" ...></recent-payments>
                    <div class="loading" *ngIf="loading">
                        <dt-loader [selectedLoader]="'ball-pulse'" wild></dt-loader>
                    </div>
            </dt-tab-content>
            <dt-tab-content tabTitle="Amount Due">
                <amount-due *ngIf="!loading" [amountDues]="amountDues" [paymentPlan]="paymentPlan"></amount-due>
                <div class="loading" *ngIf="loading">
                    <dt-loader [selectedLoader]="'ball-pulse'" wild></dt-loader>
                </div>
            </dt-tab-content>
            <dt-tab-content *ngIf="showCashierTab()" tabTitle="Cashier" class="cashier">
                <add-payment-form [payment]="payment" ...
                    (submitPaymentEvent)="submitPayment()"></add-payment-form>
            </dt-tab-content>
        </dt-tabs>
    </dt-panel-content>
</dt-panel>

这位父母&#39;组件使用以&#39;前缀为前缀的子组件 - &#39;由npm包带来。还使用了项目中的其他子组件。

使用这个,我能够获得一个我无法直接访问的子组件内的元素的引用:

this.elm.nativeElement.querySelector('dt-list-item').click();

请注意,没有&#39; dt-list-items&#39;在父视图的html中。然而,&#39; dt-tabs&#39;组件确实包含&#39; dt-list-items&#39;。我需要在第一个方法上调用click方法,以使tab组恢复到初始状态,这就是我做的方式。

希望这会对你有所帮助。

答案 1 :(得分:0)

在e2e中,我们可以像下面这样直接查询DOM

async getDetails() {
        return await browser.executeScript('return ng.probe(document.querySelector("mat-table")).componentInstance._data');
    }

无论您是否使用chrome控制台,我们都可以像上面一样获取数据

相关问题