Angular 2.0.0-模拟组件 [英] Angular 2.0.0 - Mocking Components

查看:72
本文介绍了Angular 2.0.0-模拟组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular 2.0.0 Final Release中模拟组件?我在模拟一个组件时遇到问题,该组件具有一个变量,该变量用于另一个组件中的逻辑.具体来说,我想模拟 PrimeNG数据表选择.

How do you mock a component in Angular 2.0.0 Final Release? I have a problem in mocking a component that has a variable that I use for logic in another component. Specifically, I want to mock a PrimeNG Datatable selection.

下面的示例代码.

table.component.html

        <p-dataTable
          #table
          [value]="myDatasource"
          [(selection)]="mySelections"
          ...
        >

table.component.ts

@Component({
  selector: 'my-table',
  templateUrl: './table.component.html'
})

export class TableComponent{
    @ViewChild('table') datatable;

my-component.component.html

<my-table #mytable></my-table>

my-component.component.ts

@Component({
  selector: 'my-component',
  templateUrl: './my-component.component.html'
})

export class MyComponent {
  @ViewChild('#mytable') mytable;

  myFunction() : void  {
    if(this.mytable.table.selection.length === 0){
       console.log();
    } else{
       console.log();
    }
  }

如何模拟它,以便可以将值设置为 table.component.ts 中的 选择 ,以在 my-component.component.ts ?

How do I mock it so that I can set values to the selection in the table.component.ts to test in the my-component.component.ts?

推荐答案

香蕉箱[()]语法只是[] ()的简写,其中输出()的名称只是输入[],后缀为Change.例如

The banana-box [()] syntax is just shorthand for [] (), where the name of the output () is just the name of the input [], suffixed with Change. For example

import { Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'p-datatable',
  template: `...`
})
class MockDataTable {
  @Input() value;

  @Input() selection;
  @Output() selectionChange = new EventEmitter();
}

此处,输出selectionChange与输入selection是相同的名称,只是后缀为Change.现在我们可以使用语法[(selection)].当我们向selectionChange发出值时,Angular将相应地更改我们为其分配的属性.例如

Here the output selectionChange is the same name as the input selection, just suffixed with Change. Now we can use the syntax [(selection)]. When we emit a value to the selectionChange, Angular will change the property that we assign to it accordingly. For example

@Component({
  template: '<p-datatable [(selection)]="value"></p-datatable>
})
class ParentComponent {
  value = somevalue;
}

class MockDataTable {
  @Output() selectionChange = new EventEmitter();

  click() {
    this.selectionChange('new value');
  }
}

在这里,当在数据表上调用click时,它将发出一个值为new value的新事件.因为ParentComponent.value绑定到selectionChange,所以Angular会自动将其值更改为new value.

Here, when click is called on the data table, it emits a new event with the value new value. Because the ParentComponent.value is bound to the selectionChange, Angular will automatically change its value to new value.

这篇关于Angular 2.0.0-模拟组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆